0

I would like to create a code from a given image. For example, this image:

enter image description here

should get the code 111-111-010.

(Suppose it's a png image and all pixels except the banana itself are transparent.)

If all pixels in a particular square are transparent, the value of this square is 0, otherwise it's 1.

So, given an image, I would like to divide it to squares of a given size (e.g. the banana image is 300x300 pixels, and the squares are 100x100), and then to create a code (string) which is built like described above.

The easiest way would probably be by using each_pixel and just check manually if all pixels in a square are transparent. Is there a better method?

Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746

1 Answers1

0

I would take your existing image and shrink it to that 3x3 size:

play = image.resize(3, 3, CubicFilter, 0.5)

Then you can create the code by checking each remaining pixel using:

code = ""
(0..2).each do |ix|
  (0..2).each do |iy|
    code += play.pixel_color(ix,iy).opacity == 65535 ? "0" : "1"
    code += iy == 2 ? "-" : "" unless ix == 2 && iy == 2
  end
end

I compare opacity to 65535 because when I inspected a pixel I knew was transparent this is what returned:

=> red=65535, green=65535, blue=65535, opacity=65535 
innonate
  • 159
  • 5