Store pixel color in data frame

Viewed 377

I want to load a (black white) picture (.png) by using PILLOW and get the grey value for each pixel. Later I want to store the value for each pixel in a pd.DataFrame like so:

        x    y    z
0      13    0  115
1      14    0  116
2      15    0  120
3      16    3  122
4      17    4  119

where x, y are the coordinates of the pixels and z is the color. (Only z-values more than a specific value (e.g. 100) should be saved in the dataframe). My code for now:

img = Image.open(...)
img = img.convert('LA')

pixels = img.load()

x =[]
y =[]
z =[]

def test(x,y):
    return int(pixels[x,y][0])

size = 200
for i in range(size):
    for j in range(size):
        if test(j,i)>100:
            x+=[j]
            y+=[i]
            z+=[test(j,i)]

f=(x,y,z)
df = pd.DataFrame(data=[f[0],f[1],f[2]]).T

I have the feeling that this is not the best way how to handle the problem. Also when I have very large pictures this method seems to be very slowly. As I want to do clustering based on this DataFrame I am looking for a solution that is very fast, as the clustering itself will take some time afterwards.

Looking forward for suggestions!:)

1 Answers

I wouldn't be looking to Pandas for image processing, but if that is what you want to do, you can get there like this:

import numpy as np
from PIL import Image

# Load image and convert to greyscale - NOT greyscale plus alpha!
Image.open('paddington.png').convert('L')

# Make into Numpy array
na = np.array(im)

# Find X, Y locations of all pixels exceeding 100
Y, X = np.where(na>100)

# Grab greyscale values at those coordinates
Z = na[Y, X]

So, at this point you will have 3 Numpy arrays with your X, Y and Z values in them and you can put them into Pandas... or use an image processing tool like SciPy, OpenCV, scikit-image.

Related