python-2.7 - 如何在 Python 中使用 OpenCV 合并 2 个灰度图像

标签 python-2.7 opencv merge channel

我想用 OpenCv 合并方法合并 2 个单 channel 灰度图像。它是下面的代码:

...
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
zeros = numpy.zeros(img_gray.shape)
merged = cv2.merge([img_gray, zeros])
...

问题是灰度图像没有应该为1的深度属性,并且合并功能需要相同大小的图像和相同的深度。我得到错误:
error: /build/buildd/opencv-2.4.8+dfsg1/modules/core/src/convert.cpp:296: error: (-215) mv[i].size == mv[0].size && mv[i].depth() == depth in function merge

我怎样才能合并这个数组?

最佳答案

已解决,我必须更改 img_gray 的 dtype来自 uint8float64

img_gray = numpy.float64(img_gray)

OpenCV 版本 2.4.11
import numpy as np
# Load the image
img1 = cv2.imread(paths[0], cv2.IMREAD_UNCHANGED)

# could also use cv2.split() but per the docs (link below) it's time consuming
# split the channels using Numpy indexing, notice it's a zero based index unlike MATLAB
b = img1[:, :, 0]
g = img1[:, :, 1]
r = img1[:, :, 2]

# to avoid overflows and truncation in turn, clip the image in [0.0, 1.0] inclusive range
b = b.astype(np.float)
b /= 255

操纵 channel ......在我的情况下,将高斯噪声添加到蓝色 channel ( b => b1 )
b1 = b1.astype(np.float)
g = g.astype(np.float)
r = r.astype(np.float)

# gotcha : notice the parameter is an array of channels
noisy_blue = cv2.merge((b1, g, r))

# store the outcome to disk
cv2.imwrite('output/NoisyBlue.png', noisy_blue)

注意:
  • 或者,您也可以在 astype 中使用 np.double 代替 np.float 进行类型转换
  • Open CV Documentation Link
  • 关于python-2.7 - 如何在 Python 中使用 OpenCV 合并 2 个灰度图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29847841/

    相关文章:

    python - 将连接的组件分离到多个图像

    opencv - PCA如何用于SIFT或VLAD载体?

    r - 合并大量逻辑向量

    r - 通过在 r 中保留某些列值来合并两个数据帧

    python - 在 Python 中合并两个对象

    Python - 在 List.Sort 中使用 Lambda

    python - Python 2.7 中的几何级数

    python - 在 Python 2.7x 中调用 u'\123 4'.decode(' utf-8') 是什么意思?

    python - 在python中获取MAC地址并附加到字符串

    python - CSRT 算法不更新目标