如何在Python中将2个灰度图像与OpenCV合并

时间:2015-04-24 12:42:35

标签: python-2.7 opencv merge channel

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

...
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

如何合并这些数组?

1 个答案:

答案 0 :(得分:2)

解决了,我必须将img_gray的dtype从uint8更改为float64

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

操纵通道......在我的情况下,将高斯噪声添加到蓝色通道(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)

N.B: