Home > Blockchain >  Could not broadcast input array from shape - OpenCV Python
Could not broadcast input array from shape - OpenCV Python

Time:11-10

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 1280x622 & my logo image(logo-png) size is 160x160. I'm inserting the logo as,

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.

CodePudding user response:

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.

  • Related