I am trying to find the contrast of an image using ChunkyPNG. Is there any way to get the standard deviation of an image using ChunkyPNG?
Asked
Active
Viewed 130 times
0
-
Which image param do you want to calculate the standard deviation? – Thiago Lewin Nov 27 '13 at 18:43
-
color of the pixels? Assuming there is just one channel (grayscale). – Hommer Smith Nov 27 '13 at 18:46
1 Answers
2
Looking at the ChunkyPNG code, I couldn't find any stats module.
But you can use the following method:
image = ChunkyPNG::Image.from_file('any PNG image file')
# @return [Hash] some statistics based on image pixels
def compute_image_stats(image, &pixel_transformation)
# compute pixels values
data = image.pixels.map {|pixel| yield(pixel)} # apply the pixel convertion
# compute stats
n = data.size # sum of pixels
mean = data.inject(:+).to_f / n
variance = data.inject(0) {|sum, item| sum += (item - mean)**2} / n
sd = Math.sqrt(variance) # standard deviation
{mean: mean, variance: variance, sd: sd}
end
# compute stats for grayscale image version
compute_image_stats(image) {|pixel| ChunkyPNG::Color.grayscale_teint(pixel)}
# compute stats for blue channel
compute_image_stats(image) {|pixel| ChunkyPNG::Color.b(pixel)}
I included all stats in the return, because they were computed for standard deviation (sd) calculation.

Thiago Lewin
- 2,810
- 14
- 18
-
Thanks for taking the time on doing this. Really useful. I will try it out – Hommer Smith Nov 27 '13 at 19:59
-
I have a question. Is there any way I could get the standard deviation normalized in a value between 0 and 1. When using ImageMagick standard deviation, I get ```standard deviation: 105.973 (0.415581)``` and the parentheses value is always in the range 0 to 1. So if multiplied by 100, it is percent of max value – Hommer Smith Nov 27 '13 at 21:21
-
ImageMagick divides by the maximum that the variable can reach. In the grayscale image the maximum is 255, so: `105.973/255 = 0.41558`. – Thiago Lewin Nov 27 '13 at 21:43