我正在尝试确定图片的一部分是否包含红白条纹物体(liftramp)。如果它存在,它看起来像这样: ,如果不这样:
天真的方法是提取直方图,并计算红色像素是否比蓝色/绿色像素多:
use Image::Magick;
my $image = Image::Magick->new;
my $rv = $image->Read($picture);
#$rv = $image->Crop(geometry=>'26x100+484+40');
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 };
}
my $total=0;
foreach my $v (@hist_entries) {
if ($$v{r}>($$v{g}+$$v{b})) { $total +=$$v{count}; }
}
然后比较是否
$total > 10
(任意阈值)。虽然这在相对晴朗的日子似乎很有效(存在时为 50-180,不存在时为 0-2),但厚重的云层和黄昏使检测总是说电梯不存在。我想必须有更聪明的方法来检测是否存在红白色物体。所以问题是如何更可靠地进行检测?
请注意,灰色/绿色背景可能会随着季节而变化为更多的灰棕色或其他颜色。我也不能指望像素精度,因为它可能会移动一点(或者我只是裁剪 3-4 个像素并查看它们是否为红色) - 但它应该主要适合他裁剪的框。
最佳答案
另一种对光照更不敏感的方法是在转换为 HSV 色彩空间后寻找红色色调。但是由于红色与黑色/灰色/白色具有相同的 0 色相,因此我会反转图像,使红色变为青色。因此,在反转并转换为 HSV 后对色调 channel 进行直方图,并在 0 到 255 范围内寻找青色色调接近 180 度或相当于 50% 灰度或 128 的值。在 imagemagick 中,你会这样做
convert XqG0F.png -negate -colorspace HSV -channel red -separate +channel -define histogram:unique-colors=false histogram:without_hist.png
convert x5hWF.png -negate -colorspace HSV -channel red -separate +channel -define histogram:unique-colors=false histogram:with_hist.png
因此,您可以在第二张图像(红色条)中看到,在中间附近有一个很大的宽峰,即 50%(水平),但在该区域的第一张图像中没有。
关于perl - 使用直方图来确定有色物体的存在?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43915852/