Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top