1

Is there a way to sample the color (know what is the color or the range of colors) in a specific area in a given image using perl? Let's say I have a 200X200 image and I want to sample the color (or colors) in the area X: 15; Y: 30;. Is there a way to do this? Or is there any existing module that could make this easy to implement (especially given that there are many areas to sample within in an image and that there are many images).

Thanks!

Fred

  • 1
    Possible solution: http://stackoverflow.com/questions/3681415/perl-imagemagick-getting-color-values-by-pixel – Mark Nov 14 '11 at 17:24

2 Answers2

2

First, let me state up front that I do not understand color spaces. However, GD would make it easy to grab a bunch of pixels from a bitmap.

#!/usr/bin/env perl

use strict;
use warnings;

use GD;

my $img = GD::Image->new('Palisades-woods.jpg');

my ($width, $height) = $img->getBounds;

my $sample_left = $width  / 2 - 10;
my $sample_top  = $height / 2 - 10;
my $sample_width = my $sample_height = 20;

my $n = 0;
my $avg = 0;

for my $y (0 .. $sample_height - 1) {
    for my $x (0 .. $sample_width - 1) {
        my ($r, $g, $b) = $img->rgb( $img->getPixel($x, $y));
        my $rgb =  ($r << 16) + ($g << 8) + $b;
        $avg = ($n * $avg + $rgb) / ($n + 1);
        $n += 1;
    }
}

printf "Average rgb is #%06X\n", $avg;
Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
0

I haven't had a chance to test this out yet but it looks like its anything you could ask for dealing with images and perl. http://www.graphicsmagick.org/perl.html

John Riselvato
  • 12,854
  • 5
  • 62
  • 89