Pixel by pixel data in Python -


i want following:

  • load png image python code
  • get pixel pixel rgb data in 3 arrays, 1 each r, g , b. mean r[i,j] should give me value of r @ i,j th pixel of image.
  • once have arrays can edit data.
  • plot edited data using 3 array r,g , b , save png image

how in python?

use pil load image:

from pil import image img = image.open('yourimage.png') 

i'm going suggest method messes directly image data, without accessing individual pixels coordinates.

you can image data in 1 big byte string:

data = img.tostring() 

you should check img.mode pixel format. assuming it's 'rgba', following code give separate channels:

r = data[::4] g = data[1::4] b = data[2::4] = data[3::4] 

if want access pixels coordinate like:

width = img.size[0] pixel = (r[x+y*width],g[x+y*width],b[x+y*width],a[x+y*width]) 

now put together, there's better way, can use zip:

new_data = zip(r,g,b,a) 

and reuce:

new_data = ''.join(reduce(lambda x,y: x+y, zip(r,g,b,a))) 

then save picture:

new_img = image.fromstring('rgba', img.size, new_data) new_img.save('output.png') 

and here's in example zeros red channel:

from pil import image img = image.open('yourimage.png')  data = img.tostring() r = data[::4] g = data[1::4] b = data[2::4] = data[3::4]  r = '\0' * len(r)  new_data = ''.join(reduce(lambda x,y: x+y, zip(r,g,b,a))) new_img = image.fromstring('rgba', img.size, new_data) new_img.save('output.png') 

Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -