Python Forum
problem adding two numpy arrays - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: problem adding two numpy arrays (/thread-28444.html)



problem adding two numpy arrays - djf123 - Jul-19-2020

I am trying to do the following. I want to add the Mona Lisa .jpg image at this link to a slightly larger numpy array of all zeroes (called base_image1) of size (605,405,4). Alpha channel values was first added to the Mona Lisa image and converted to a numpy array (called image1) of size (599,402,4).

Next, I add the smaller Mona Lisa image to a location within the larger numpy array of all zeroes. Finally I display the resulting image.

What I was expecting to get displayed was an image of the Mona Lisa with a little bit of white border in certain regions. Instead it simply displays a (605,405,4) image that looks completely white everywhere! Why is this happening? I can't understand why this is occuring Wall . Below is my code:
import numpy as np
from PIL import Image

#Load Mona Lisa image and Add fully opaque alpha channel values
path='C:\\Users\\john\\Desktop\\monalisa.jpg'
image = Image.open(path)
image.putalpha(255)

#Make larger numpy array of all zeroes
base_image1=np.zeros((605, 405, 4),dtype=int)

#Convert Mona Lisa image to numpy array and add Mona Lisa array to region within larger array
width, height = image.size
image1=np.array(image)
x=0
y=0
base_image1[x:(x+height),y:(y+width),:]=base_image1[x:(x+height),y:(y+width),:]+image1

#Display image
img = Image.fromarray(base_image1, 'RGBA')
img.show()



RE: problem adding two numpy arrays - Addweb - Aug-09-2022

import numpy as np


RE: problem adding two numpy arrays - deanhystad - Aug-09-2022

The problem is not adding the arrays, the problem is that one of the arrays has the wrong dtype. The dtype for base_image1 should be np.int8. You could have determined this by looking at the dtype for image1, or just use dtype from image1.
image = Image.open(path)
image.putalpha(255)
image1 = np.array(image)

# Make larger numpy array of all zeroes
base_image1 = np.zeros((605, 405, 4), dtype=image1.dtype)
You can copy image1 into base_image1 without the extra addition step.
base_image1[x:(x+height),y:(y+width),:] = image1