Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Could not broadcast input array from shape – OpenCV Python

I’m trying to insert an image on top of another image which was generated using a numpy array. When I write this image into a file as a jpeg, the file has written correctly.

nparr = np.frombuffer(msg.value(), np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

But when I add an image, it gives me an error as,

img[y_offset:y_offset+logo.shape[0], x_offset:x_offset+logo.shape[0]] = logo
ValueError: could not broadcast input array from shape (160,160,4) into shape (160,160,3)

My large image size(img-jpeg) is 1280×622 & my logo image(logo-png) size is 160×160. I’m inserting the logo as,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

logo = cv2.imread("logo.png", cv2.IMREAD_UNCHANGED)
x_offset=y_offset=50

img[y_offset:y_offset+logo.shape[0], x_offset:x_offset+logo.shape[0]] = logo

Is there a way to fix this as I’m new to Python and Numpy.

>Solution :

It seams that your logo image has an alpha channel. As I don’t have the image I can’t fully test, but try this:

img[y_offset:y_offset+logo.shape[0], x_offset:x_offset+logo.shape[0]] = logo[:,:,:3]

This will only put the first 3 channels (B, G and R) of logo into img.

Edit: You can also specify the way to read the image with cv2.imread():

cv2.imread("logo.png", cv2.IMREAD_COLOR)

This will leave out the alpha channel.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading