5

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?

1
  • Yes, that is what it means. It would also appear that your x,y axes are reversed. Commented Nov 5, 2014 at 19:36

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.