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

Error as I try to merge zero channels to create an image with a single channel

我正在尝试读取图像,然后在输出图像中仅保留 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

我不明白这是为什么。为什么会出现此错误?

这是因为虽然您的零形状正确,但数据类型很可能不匹配。 Numpy Zeros docs 的默认数据类型为 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 zeros
only_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))