簡體   English   中英

OpenCV - 二進制圖像中所有非零像素的位置

[英]OpenCV - locations of all non-zero pixels in binary image

如何在二進制圖像(cv :: Mat)中找到所有非零像素的位置? 我是否必須掃描圖像中的每個像素,或者是否有可以使用的高級OpenCV功能? 輸出應該是點矢量(像素位置)。

例如,這可以在Matlab中完成,簡單如下:

imstats = regionprops(binary_image, 'PixelList');
locations = imstats.PixelList;

或者,甚至更簡單

[x, y] = find(binary_image);
locations = [x, y];

編輯 :換句話說,如何在cv :: Mat中找到所有非零元素的坐標?

正如@AbidRahmanK所建議的,在OpenCV 2.4.4版中有一個函數cv::findNonZero 用法:

cv::Mat binaryImage; // input, binary image
cv::Mat locations;   // output, locations of non-zero pixels 
cv::findNonZero(binaryImage, locations);

它完成了這項工作。 此功能是在OpenCV版本2.4.4中引入的(例如,版本2.4.2中不提供)。 此外,截至目前findNonZero由於某種原因不在文檔中。

我將此作為Alex的答案中的編輯,但它沒有得到審查,所以我會在這里發布,因為它是有用的信息imho。

你也可以傳遞一個點向量,然后更容易用它們做一些事情:

std::vector<cv::Point2i> locations;   // output, locations of non-zero pixels 
cv::findNonZero(binaryImage, locations);

一般來說cv::findNonZero函數有一個注釋:如果binaryImage包含零個非零元素,它將拋出,因為它試圖分配'1 xn'內存,其中n是cv::countNonZero ,n顯然是0然后。 我通過事先手動調用cv::countNonZero避免這種情況,但我不太喜歡那個解決方案。

有人想在python中做這件事。 它也可以使用numpy數組,因此您不需要升級opencv版本(或使用未記錄的函數)。

mask = np.zeros(imgray.shape,np.uint8)
cv2.drawContours(mask,[cnt],0,255,-1)
pixelpoints = np.transpose(np.nonzero(mask))
#pixelpoints = cv2.findNonZero(mask)

注釋掉的是使用openCV的相同功能。 有關詳情,請參閱:

https://github.com/abidrahmank/OpenCV2-Python-Tutorials/blob/master/source/py_tutorials/py_imgproc/py_contours/py_contour_properties/py_contour_properties.rst

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM