Reputation: 155
I am trying to access the pixels of a grayscale image. On loading it, I found that the pixel values are transposed as well as the color of the new image 'img.png' is inverted. But ideally, 'img.png' should be same as 'cat.png'. Why are they different?
import numpy as np from PIL import Image img=Image.open('cat.png') pix=img.load() res_list=[] img_data= np.zeros((128, 128), dtype=np.uint8) for i in range(img.size[0]): for j in range(img.size[1]): img_data[i,j]=pix[i,j] img=Image.fromarray(img_data) img.save('img.png')
Also, when I tried to update img_data as:
img_data[i,j]=255-pix[i,j]
still it wasn't the actual image, but very white image. How can I recover the original image?
Upvotes: 2
Views: 990
Reputation: 76194
I agree with gelezko's suggestion to switch indexing order. This will solve the transposition problem.
The color problem appears to occur because the input image isn't actually greyscale. When I tried print img.mode
, I got "P" rather than "L". Try explicitly converting to L before doing any work on the pixels.
img=Image.open('cat.png')
img = img.convert("L")
pix=img.load()
Now you should get a properly oriented & colored image:
Upvotes: 2
Reputation: 819
Right code:
img_data[j,i]=pix[i,j]
Just swap i
and j
in img_data
.
Upvotes: 1