如何在二进制图像(cv :: Mat)中找到所有非零像素的位置?我是否必须扫描图像中的每个像素,或者是否有可以使用的高级OpenCV功能?输出应该是点矢量(像素位置).
例如,这可以在Matlab中完成,只需:
imstats = regionprops(binary_image, 'PixelList');
locations = imstats.PixelList;
Run Code Online (Sandbox Code Playgroud)
或者,甚至更简单
[x, y] = find(binary_image);
locations = [x, y];
Run Code Online (Sandbox Code Playgroud)
编辑:换句话说,如何在cv :: Mat中找到所有非零元素的坐标?
Ale*_*xey 11
正如@AbidRahmanK所建议的,cv::findNonZeroOpenCV版本2.4.4中有一个函数.用法:
cv::Mat binaryImage; // input, binary image
cv::Mat locations; // output, locations of non-zero pixels
cv::findNonZero(binaryImage, locations);
Run Code Online (Sandbox Code Playgroud)
它完成了这项工作.此功能是在OpenCV版本2.4.4中引入的(例如,版本2.4.2中不提供).此外,截至目前,由于findNonZero某种原因,不在文档中.
Ela*_*782 11
我将此作为Alex的答案中的编辑,但它没有得到审查,所以我会在这里发布,因为它是有用的信息imho.
你也可以传递一个点向量,然后更容易用它们做一些事情:
std::vector<cv::Point2i> locations; // output, locations of non-zero pixels
cv::findNonZero(binaryImage, locations);
Run Code Online (Sandbox Code Playgroud)
cv::findNonZero一般说明函数的一个注意事项:如果binaryImage包含零非零元素,它将抛出,因为它试图分配'1 xn'内存,其中n是cv::countNonZero,而n显然是0.我通过cv::countNonZero事先手动调用来避免这种情况,但我不太喜欢那种解决方案.