[英]How to save to vector coordinates of white pixels?
我想遍歷二進制化的cv::Mat
並保存所有像素坐標為255
。
cv::Mat bin;
std::vector<cv::Point2i> binVec;
int h = 0;
int white = 254; //Just for comparison with pointer of Matrix value
for (int i = 0; i < bin.rows; i++, h++) {
for (int j = 0; j < bin.cols; j++, h++) {
int* p = bin.ptr<int>(h); //Pointer to bin Data, should loop through Matrix
if (p >= &white) //If a white pixel has been found, push i and j in binVec
binVec.push_back(cv::Point2i(i, j));
}
}
此代碼段無效,我也不知道為什么。
在example.exe中的0x76C6C42D處引發了異常:Microsoft C ++異常:cv :: Exception在內存位置0x0019E4F4。
example.exe中0x76C6C42D的未處理異常:Microsoft C ++異常:內存位置0x0019E4F4的cv :: Exception。
那么我如何計算h
並讓指針工作呢?
您可以避免掃描圖像。 要將所有白色像素的坐標保存在矢量中,您可以執行以下操作:
Mat bin;
// fill bin with some value
std::vector<Point> binVec;
findNonZero(bin == 255, binVec);
您可以使用Point
代替Point2i
,因為它們是相同的:
typedef Point2i Point;
如果您確實要使用for循環,則應執行以下操作:
const uchar white = 255;
for (int r = 0; r < bin.rows; ++r)
{
uchar* ptr = bin.ptr<uchar>(r);
for(int c = 0; c < bin.cols; ++c)
{
if (ptr[c] == 255) {
binVec.push_back(Point(c,r));
}
}
}
請記住:
CV_8UC1
,而不是CV_32SC1
,因此您應該使用uchar
而不是int
。 bin.ptr<...>(i)
為您提供了指向第i行開頭的指針,因此您應該將其移出內部循環。 Point
取作為參數x
(COLS)和y
( 行 ),而你是通過i
( 行 )和j
(COLS)。 因此,您需要交換它們。 findNonZero
方法,因此在此不做介紹。 h
p
指向的值與h
進行比較,而不是將p
與h
的地址進行比較。 所以
cv::Mat bin;
std::vector<cv::Point2i> binVec;
int h = 0;
int white = 254; //Just for comparison with pointer of Matrix value
for (int i = 0; i < bin.rows; i++) {
for (int j = 0; j < bin.cols; j++) {
int* p = bin.ptr<int>(h++); //Pointer to bin Data, should loop through Matrix
if (*p >= white) //If a white pixel has been found, push i and j in binVec
binVec.push_back(cv::Point2i(i, j));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.