Skip to content

Enumerable

kkrmno edited this page Apr 18, 2020 · 2 revisions

Enumerable

Note that Image includes Enumerable. Thus, one may make use of the methods provided by the Enumerable mixin. The elements yielded by each are the pixels from top left to bottom right. Thus, the collection of pixels is the set under consideration.

Some examples of useful methods in the mixin are:

all?

Assuming a grayscale image img

#Check if all pixel values are within range of an 8-bit image.
#Should also make sure that values are integer.
img.all? {|pixel| 0 <= pixel && pixel <= 255}

count

Assuming an image img

#Counts the number of occurrences of "pxl" value in the image.
img.count(pxl)

include?

If we want to know whether a given color/grayscale value is present in an image we may use

img.include?(color)

inject / reduce

To combine using a binary operator. For example, to compute the sum of all values in a grayscale image:

img.inject(:+)
#Or equivalently
img.reduce(:+)

max

For color images, there is no obvious order, so max (and min) are not so useful, however for grayscale images, one may use

#Find the maximal grayscale value
img.max

min

For color images, there is no obvious order, so min (and max) are not so useful, however for grayscale images, one may use

#Find the minimal grayscale value
img.min

tally

Count the number of occurrences of each pixel value

#Returns a hash with the keys being the pixel values present in the image, and the values being the number of occurrences
img.tally

uniq

Returns an array of all (unique) pixel values present in the image.

#Count the number of unique colors in an image
img.uniq.length
Clone this wiki locally