我正在尝试读取图像,然后在输出图像中仅保留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文档的默认数据类型为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))