簡體   English   中英

如何保存到白色像素的矢量坐標?

[英]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方法,因此在此不做介紹。
  1. 您應該只在內循環中增加h
  2. 您應該將p指向的值與h進行比較,而不是將ph的地址進行比較。

所以

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.

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