How to get average pixel value of grayscale image in Python using PIL \ Numpy?

I have few grayscale images, and I thought about calculating the average pixel value for the overall image so that I can represent each individual image using the same value.

enter image description here

+5
source share
3 answers

If you want to do such things, you should use a scikit-image instead of a raw PIL or pillow. SciKit Image uses numpy arrays for images, so all numpy methods work.

 from skimage import io import numpy as np image = io.imread('http://i.stack.imgur.com/Y8UeF.jpg') print(np.mean(image)) 

You might want to convert all images to float to get betwenn 0 and 1 :

 from skimage import io, img_as_float import numpy as np image = io.imread('http://i.stack.imgur.com/Y8UeF.jpg') image = img_as_float(image) print(np.mean(image)) 
+8
source

This can be done using PIL by going through the pixels, accumulating all the pixel values ​​and dividing by the number of pixels (i.e. width * height)

 from PIL import Image im = Image.open('theimagefile.jpg') im_grey = im.convert('LA') # convert to grayscale width,height = im.size total=0 for i in range(0,width): for j in range(0,height): total += img.getpixel((i,j))[0] mean = total / (width * height) 
+2
source

the solution is much simpler than suggested in the comments and answers - i.e. there are no calculations on tuples and there is no need for nested loops to sort through cell values.

in particular, if you have a grayscale image, you have a 2D array in which the cells of the array are filled with scalar values ​​from 0 to 1.

on the contrary, the color image is a 2D NumPy array in which the rgb tuple is in each cell.

in a different way: representing a NumPy array of gray images is a 2D array whose cells have floating point values ​​between 0 (black) and 1 (white)

In this case, you can calculate the average pixel value by calculating the average value along both axes of the image array, for example:

 >>> import numpy as NP >>> img = NP.random.rand(100, 100) >>> img[:5, :5] array([[ 0.824, 0.864, 0.731, 0.57 , 0.127], [ 0.307, 0.524, 0.637, 0.134, 0.877], [ 0.343, 0.789, 0.758, 0.059, 0.374], [ 0.693, 0.991, 0.458, 0.374, 0.738], [ 0.237, 0.226, 0.869, 0.952, 0.948]]) 

this one line of code will do what you want - calculate the average value twice, once for each axis in the array (there is no need to specify the axis for the second call, because the return value from the first call is just a 1D array

 >>> img.mean(axis=0).mean() 0.50000646872609511 

a value of 0.5 seems correct because the values ​​of the array were generated by calling NP.random.rand, which returns values ​​selected from a uniform distribution over a half-open interval [0, 1)

 >>> import matplotlib.pyplot as MPL >>> MPL.imshow(img, cmap=MPL.cm.gray, interpolation='nearest') >>> MPL.show() 

enter image description here

+1
source

Source: https://habr.com/ru/post/1243700/


All Articles