alessandro
alessandro

Reputation: 3984

write matrix to image by PIL

I have a 2D matrix that I want to write as a PBM file (it's only -1,1 values, black&white).

I just discovered about PIL, but the following approach does not work:

im = Image.new('L', (self.nx,self.ny))  
data=[[255*(self.spins[i][j][0].m+1)/2 for j in range(0,self.ny)]for i in range(0,self.nx)]  
im.putdata(data)   
im.save('my_image.pbm')  

that is, I get my PBM file with its header, but no data:

P5  
4 3  
255  

if somebody can help me here...

thank you!

alessandro

Upvotes: 1

Views: 863

Answers (1)

Gabriel Reid
Gabriel Reid

Reputation: 2536

Image.putdata takes a one-dimensional sequence, not a multi-dimensional sequence like what you've got in your code.

I.e. instead of using something like

[[v1, v2, v3],
 [v4, v5, v6],
 [v7, v8, v9]] 

to hold your pixel data that is being passed to putdata, it should be

[v1, v2, v3, v4, v5, v6, v7, v8, v9]

Upvotes: 3

Related Questions