我尝试合并零通道以创建具有单个通道的图像时出错

我正在尝试读取图像,然后仅保留red输出图像中的通道。这是我所做的:


color = cv2.imread("lohri.jpg")

b,g,r = cv2.split(color)

zeros = np.zeros([b.shape[0], b.shape[1]])

# Make other 2 channels as zeros

only_red = cv2.merge((zeros, zeros, r))

但是当我这样做时,我收到一条错误消息:


OpenCV(3.4.1) Error: Assertion failed (mv[i].size == mv[0].size && mv[i].depth() == depth) in merge, file /io/opencv/modules/core/src/merge.cpp, line 458

Traceback (most recent call last):

File "inspect.py", line 23, in <module>

  only_red = cv2.merge((zeros, zeros, r))

  cv2.error: OpenCV(3.4.1) /io/opencv/modules/core/src/merge.cpp:458: 

  error: (-215) mv[i].size == mv[0].size && mv[i].depth() == depth in 

  function merge

我无法理解这样做的原因。为什么我会收到这个错误?


眼眸繁星
浏览 239回答 1
1回答

守着星空守着你

这是因为虽然您的零形状是正确的,但很可能是数据类型不匹配。Numpy Zeros文档的默认数据类型为numpy.float64. 只需dtype为您的案例传递参数。color = cv2.imread("lohri.jpg")b,g,r = cv2.split(color)zeros = np.zeros(b.shape[0], b.shape[1]], dtype = b.dtype)#Note that the dtype is most likely np.uint8, and you can use that instead too if you prefer#zeros = np.zeros([b.shape[0], b.shape[1]], dtype = np.uint8)#Also note that you can pass shape tuple directly.#zeros = np.zeros(b.shape, dtype = np.uint8)# Make other 2 channels as zerosonly_red = cv2.merge((zeros, zeros, r))编辑:您还可以使用np.zeros_like正确的形状和数据类型创建数组,这也使代码更加简洁明了。谢谢马克!color = cv2.imread("lohri.jpg")b,g,r = cv2.split(color)zeros = np.zeros_like(b)only_red = cv2.merge((zeros, zeros, r))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python