Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - ValueError: operands could not be broadcast together with shapes [duplicate]

I am trying to implement face recognition by Principal Component Analysis (PCA) using python. One of the steps is to normalize the input (test) image T by subtracting the average face vector m: n = T - m.

Here is my code:

#Step1: put database images into a 2D array
filenames = glob.glob('C:\\Users\\Karim\\Downloads\\att_faces\\New folder/*.pgm')
filenames.sort()
img = [Image.open(fn).convert('L').resize((90, 90)) for fn in filenames]
images = np.asarray([np.array(im).flatten() for im in img])

#Step 2: find the mean image and the mean-shifted input images
m = images.mean(axis=0)
shifted_images = images - m

#Step 7: input image
input_image = Image.open('C:\\Users\\Karim\\Downloads\\att_faces\\1.pgm').convert('L').resize((90, 90))
T = np.asarray(input_image)
n = T - mean_image

But I am getting an error Traceback (most recent call last): File "C:/Users/Karim/Desktop/Bachelor 2/New folder/new3.py", line 46, in <module> n = T - m ValueError: operands could not be broadcast together with shapes (90,90) (8100)

like image 811
user2229953 Avatar asked Sep 13 '26 11:09

user2229953


1 Answers

mean_image was computed for flattened arrays:

images = np.asarray([np.array(im).flatten() for im in img])
mean_image = images.mean(axis=0)

and input_image is 90x90. Hence the error. You should either flatten the input image, too, or not flatten the original images (I don't quite understand why you do it), or resize mean_image to 90x90 just for this operation.

like image 192
Lev Levitsky Avatar answered Sep 15 '26 03:09

Lev Levitsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!