How to select a specific horizontal line of pixels in an image to analyze on Python?

1.3k Views Asked by At

I'm beginner on Python and started trying to program a code to analyze a spray image and plot a 'gray scale value' to see the spray pattern.

For a while I have this code:

from PIL import Image
import numpy as np
    
import matplotlib.pyplot as plt
    
filepath = "flat2.jpg"
          
img = Image.open(filepath).convert('L')
    
    
WIDTH, HEIGHT = img.size
pix = img.load()
    
data = np.asarray(img.getdata())
data = data.reshape((HEIGHT,WIDTH))
    
fig,ax = plt.subplots()
reduced_data = data.mean(axis=0)
    
ax.plot(reduced_data)
    
plt.show()

However, this code analyze the entire image and I need just a specific line, like the line 329 or something. As a mitigation I tried crop the image too, but was unsucessfully.

I'm trying to do a code like the tool "plot profile" on Image J.

Obsviously I just "made" this code with a help from some users here.

Flat fan spray image.

The line and imageJ plot profile

1

There are 1 best solutions below

1
Yuri Khristich On

Since after several hours nobody supplied us with a sample of a correct efficient solution, here is the crop mitigation:

from PIL import Image

filepath = 'flat2.jpg'
img = Image.open(filepath).convert('L')

WIDTH, HEIGHT = img.size
LINE = 329         # <---- put here your desired line number

img = img.crop( (0, LINE, WIDTH, LINE+1 ) ).save('crop.png')
img = Image.open('crop.png')

# do stuff

# WIDTH, HEIGHT = img.size
# pix = img.load()
# etc

It should work but it's not exactly a correct and efficient solution at all. I believe it should be done via numpy etc.

As for the crop() function, it's a very simple thing. It just takes some rectangular area (box) from a given image. The four numbers inside the brackets (x1, y1, x2, y2) are tuple of coordinates of this box. Top-left corner (x1, y1) bottom-right corner (x2, y2). The only possible trouble is if any of this coordinates fall outside of image size.