julz12
julz12

Reputation: 417

Python - get white pixels of image

I'm would like to go from an image filename to a list of coordinates of the white pixels in the image.

I know it involves PIL. I have tried using Image.load() but this doesn't help because the output is not indexable (to use in a for loop).

Upvotes: 2

Views: 5183

Answers (1)

John Powell
John Powell

Reputation: 12581

You can dump an image as a numpy array and manipulate the pixel values that way.

from PIL import Image
import numpy as np
im=Image.open("someimage.png")
pixels=np.asarray(im.getdata())
npixels,bpp=pixels.shape

This will give you an array whose dimensions will depend on how many bands you have per pixel (bpp above) and the number of rows times the number of columns in the image -- shape will give you the size of the resulting array. Once you have the pixel values, it ought to be straightforward to filter out those whose values are 255

To convert a numpy array back to an image use:

im=Image.fromarray(pixels)

Upvotes: 2

Related Questions