feca
feca

Reputation: 31

python - how to get average pixel intensities along a line of an image and plot them on a graph?

I have a grayscale image. I want to generate a histogram that corresponds to average pixel intensity of each line along x and y axis.

for example this image should produce two histograms that look like bell curves

Upvotes: 0

Views: 5101

Answers (3)

Jan Christoph Terasa
Jan Christoph Terasa

Reputation: 5935

I'd use PIL/pillow, numpy and matplotlib

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

# load Image as Grayscale
i = Image.open("QWiTL.png").convert("L")
# convert to numpy array
n = np.array(i)

# average columns and rows
# left to right
cols = n.mean(axis=0)
# bottom to top
rows = n.mean(axis=1)

# plot histograms
f, ax = plt.subplots(2, 1)
ax[0].plot(cols)
ax[1].plot(rows)
f.show()

Upvotes: 2

Will Rosenberg
Will Rosenberg

Reputation: 61

I would refer to this previously asked question, which discusses how to find the average pixel intensity for an entire image. You can edit this code and instead of looping over every pixel, just loop line by line and then you will have an array of intensity values. Then, graph your data using the code below:

import matplotlib.pyplot as plt

#number of bins in the histogram. You can decide
n_bins = 20

fig, axs = plt.subplots(1, 1, tight_layout=True)
axs[0].hist(x, bins=n_bins)
#x is your array of values

Note: You need to download matplotlib

Upvotes: 0

Tomer Singal
Tomer Singal

Reputation: 1

Assuming your image is a numpy array, you can get the width and height from image.shape

pixel_sums_x = [sum(row) for row in image]
pixel_avgs_x = [s / image_height for s in pixel_sums_x]

pixel_sums_y = [sum(col) for col in zip(*image)]
pixel_avgs_y = [s / image_width for s in pixel_sums_y]

Using statistics library:

pixel_avgs_x = [statistics.mean(row) for row in image]
pixel_avgs_y = [statistics.mean(col) for col in zip(*image)]

Then you can plot the histograms using matplotlib https://matplotlib.org/3.1.1/gallery/statistics/hist.html

Upvotes: 0

Related Questions