Suhail Gupta
Suhail Gupta

Reputation: 23206

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

I am trying to read an image and then keep only the red channel in the output image. Here is what I did:

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

But as I do this, I get an error saying:

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

I could not understand the reason for this. Why do I get this error?

Upvotes: 1

Views: 914

Answers (1)

Paritosh Singh
Paritosh Singh

Reputation: 6246

This is because while your shape of zeros is correct, there is most likely a datatype mismatch. Numpy Zeros docs has a default datatype of numpy.float64. Just pass the dtype parameter for your case.

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

EDIT: You can also use np.zeros_like to have the array created with the correct shape and data type, Which also makes the code more clean and concise. Thanks Mark!

color = cv2.imread("lohri.jpg")
b,g,r = cv2.split(color)
zeros = np.zeros_like(b)
only_red = cv2.merge((zeros, zeros, r))

Upvotes: 2

Related Questions