I'm using PIL to get the red values from every pixel of a picture. However, I need all the values to be in numpy arrays, because as far as I know, that is the only way to plot a 3D graph with a colourmap.
The problem is when I try to find the required red values using getpixel()
, I get the following error:
Traceback (most recent call last):
File "C:\Users\Elitebook\Desktop\PIL\Smoke\get_data_smoke.py", line 14, in <module>
Z=im_rgb.getpixel((X,Y))[0]
File "C:\Users\Elitebook\AppData\Roaming\Python\Python37\site-packages\PIL\Image.py", line 1436, in getpixel
return self.im.getpixel(xy)
TypeError: an integer is required
So far, I have tried using x=x.astype(int)
and dtype
to get integer values, but none of them worked.
Here is my code:
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
im=Image.open("smoke.jpg")
im_rgb=im.convert("RGB")
w,h=im.size
x=np.arange(1,w 1,1)
y=np.arange(1,h 1,1)
X,Y=np.meshgrid(x,y)
Z=im_rgb.getpixel((X,Y))[0]
fig=plt.figure()
ax=fig.add_subplot(projection='3d')
ax.plot(X,Y,Z)
plt.show()
CodePudding user response:
If you want the image as a Numpy array, just use:
na = np.array(im_rgb)
CodePudding user response:
Your problem is that getpixel
needs a sequence of integers. Your inputs X
and Y
were arrays. Therefore, you need some form of loop to extract the individual indexes:
x = np.arange(1,w 1,1)
y = np.arange(1,h 1,1)
X,Y = np.meshgrid(x,y)
Z = []
for i,j in zip(X,Y):
for ii, jj in zip(i,j):
Z.append(im_rgb.getpixel((int(ii),int(jj))))