Reputation: 50832
I need to extract color information of images in order to be able to search for images based on a percentage of a color later on. I would like to use ImageMagick for this. Any ideas?
Upvotes: 3
Views: 1503
Reputation: 239712
ImageMagick has a Histogram
method that returns a list of colors in an image and how often they appear. It's poorly documented and has a lousy interface, but I've used it in the past, so I have some helpful code to provide:
my @hist_data = $image->Histogram;
my @hist_entries;
# Histogram returns data as a single list, but the list is actually groups of
# 5 elements. Turn it into a list of useful hashes.
while (@hist_data) {
my ($r, $g, $b, $a, $count) = splice @hist_data, 0, 5;
push @hist_entries, {
r => $r,
g => $g,
b => $b,
alpha => $a,
count => $count,
};
}
# Sort the colors in decreasing order
@hist_entries = sort { $b->{count} <=> $a->{count} } @hist_entries;
However, depending on what you're trying to do, Histogram isn't as useful as it could be for full-color images, because there will be very many slightly different shades of the same color, with the counts split among them in the histogram. A useful pre-processing step is to call $image->Segment(colorspace => 'rgb')
on a clone of the image, which finds areas of similar colors and replaces the entire area with its average color. Then when you call Histogram
you will see larger counts for fewer colors, and somewhat more representative data.
Upvotes: 7