问题描述
我正在寻求有关如何在 CImg 库中使用 label() 功能的帮助。我想做的很简单。我有一个白色背景,大黑点彼此分开,我只想计算它们。我认为 label() 是可能的,但我不明白这个函数的参数。 谢谢你的帮助!
图书馆信息': [1]:https://cimg.eu/reference/structcimg__library_1_1CImg.html#aaff4a10071470e4cd255653c5c2f043e
解决方法
基本上,您传递给它一个图像,它返回另一个图像,其中每组相似像素被分配到同一类,即它具有相同的灰度强度。所以,如果我们从这个开始:
然后运行:
#include "CImg.h"
#include <iostream>
using namespace cimg_library;
using namespace std;
int main()
{
// Create solid white image
CImg<unsigned char> img(320,240);
img.fill(255);
// Draw some black circles
unsigned char black[] = {0};
img.draw_circle(50,50,30,black);
img.draw_circle(130,100,black);
img.draw_circle(200,200,35,black);
img.draw_circle(280,140,black);
img.save("start.png");
// Label the connected components
CImg<> labels = img.label(true,64);
// Save result
labels.save("result.png");
}
我们会得到这个:
这是非常平庸的,直到我们查看直方图 - 我在这里使用 ImageMagick:
identify -verbose result.png
Image:
Filename: result.png
Format: PNG (Portable Network Graphics)
Mime type: image/png
Class: PseudoClass
Geometry: 320x240+0+0
Units: Undefined
Colorspace: Gray
Type: Grayscale
Base type: Undefined
Endianness: Undefined
Depth: 8-bit
Channel depth:
Gray: 8-bit
Channel statistics:
Pixels: 76800
Gray:
min: 0 (0)
max: 4 (0.0156863)
mean: 0.565234 (0.00221661)
median: 0 (0)
standard deviation: 1.13898 (0.00446658)
kurtosis: 2.3448
skewness: 1.89382
entropy: 0.520843
Colors: 5
Histogram:
59036: (0,0) #000000 gray(0) <--- HERE
2909: (1,1,1) #010101 gray(1)
8005: (2,2,2) #020202 gray(2)
2909: (3,3,3) #030303 gray(3)
3941: (4,4,4) #040404 gray(4)
并且您可以看到有 5 个不同的灰度值,对应于输入图像中的 5 个分量。我还可以对图像进行对比度拉伸,以便您可以看到组件,每个组件都具有不同的强度:
magick result.png -auto-level z.png
true
参数告诉 CImg 将任何像素的东北、东南、西南和西北组件视为已连接。如果您设置此 false
,它只会考虑要连接的任何像素的北、南、东和西邻居。
阈值表示一个像素可能与同类中的其他像素不同,同时仍被认为足够相似以成为邻居 - 因此它是颜色匹配的容差。
关键字:C++、CImg、图像处理、标签、标签、连通分量分析、blob 分析。