I'm just wondering is there a way to import an image in python using numpy and PIL to make it a 2D array? Furthermore if I have a black and white image is it possible to set the black to 1 and white to zero?
currently I'm using:
temp=np.asarray(Image.open("test.jpg"))
frames[i] = temp #frames is a 3D array
With this I get an error:
ValueError: operands could not be broadcast together with shapes (700,600) (600,700,3)
I'm new to python but as far as I can tell this means that basically temp is a 3D array and i'm assigning it to a 2D array?
I'm not an expert but I can think of some ways, not sure what you want to achieve though so you might not like my solutions:
from PIL import Image
from numpy import*
temp=asarray(Image.open('test.jpg'))
for j in temp:
new_temp = asarray([[i[0],i[1]] for i in j]) # new_temp gets the two first pixel values
Furthermore, you can use .resize():
from PIL import Image
from numpy import*
temp=asarray(Image.open('test.jpg'))
x=temp.shape[0]
y=temp.shape[1]*temp.shape[2]
temp.resize((x,y)) # a 2D array
print(temp)
And if you convert the picture to black&white, the array becomes 2D automatically:
from PIL import Image
from numpy import*
temp=Image.open('THIS.bmp')
temp=temp.convert('1') # Convert to black&white
A = array(temp) # Creates an array, white pixels==True and black pixels==False
new_A=empty((A.shape[0],A.shape[1]),None) #New array with same size as A
for i in range(len(A)):
for j in range(len(A[i])):
if A[i][j]==True:
new_A[i][j]=0
else:
new_A[i][j]=1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With