How can I fix my problem with merging channels in OpenCv in Python?

Viewed 487

I simply imported an image. I want to merge each BGR channel with zero arrays and then show them. I've written my code as follows:

import cv2
import numpy as np
image = cv2.imread('./images/input.jpg')

B, G, R = cv2.split(image)

zeros = np.zeros((image.shape[:2]), dtype = 'int8')

cv2.imshow("Red", cv2.merge([zeros1, zeros1, R]))
cv2.imshow("Green", cv2.merge([zeros, G, zeros]))
cv2.imshow("Blue", cv2.merge([B, zeros, zeros]))

cv2.waitKey(500)
cv2.destroyAllWindows()

After running this code I get the following error.

error                                     Traceback (most recent call last)
<ipython-input-13-9252d63ed763> in <module>
      7 zeros = np.zeros((image.shape[:2]), dtype = 'int8')
      8 
----> 9 cv2.imshow("Red", cv2.merge([zeros1, zeros1, R]))
     10 cv2.imshow("Green", cv2.merge([zeros, G, zeros]))
     11 cv2.imshow("Blue", cv2.merge([B, zeros, zeros]))

error: OpenCV(4.1.1) C:\projects\opencv-python\opencv\modules\core\src\merge.dispatch.cpp:129: error: (-215:Assertion failed) mv[i].size == mv[0].size && mv[i].depth() == depth in function 'cv::merge'

It seems correct to me. what is the problem and how can I Fix this?

2 Answers

here's the error:


zeros = np.zeros((image.shape[:2]), dtype = 'int8')

dtype should be the same as the image so uint8.

BTW I think you want to just show the image and you don't care about merging?

Then you can just do the convert from GRAY to BGR with a single channel:

cv2.imshow("Red", cv2.cvtColor(R, cv2.COLOR_GRAY2BGR))
cv2.imshow("Green", cv2.cvtColor(G, cv2.COLOR_GRAY2BGR))
cv2.imshow("Blue", cv2.cvtColor(B, cv2.COLOR_GRAY2BGR))

In this line:

zeros = np.zeros((image.shape[:2]), dtype = 'int8') 

change the dtype to 'uint8'

Related