簡體   English   中英

c ++和opencv獲取並將像素顏色設置為Mat

[英]c++ and opencv get and set pixel color to Mat

我正在嘗試將某個像素的新顏色值設置為 cv::Mat 圖像,我的代碼如下:

    Mat image = img;
    for(int y=0;y<img.rows;y++)
    {
        for(int x=0;x<img.cols;x++)
        {
        Vec3b color = image.at<Vec3b>(Point(x,y));
        if(color[0] > 150 && color[1] > 150 && color[2] > 150)
        {
            color[0] = 0;
            color[1] = 0;
            color[2] = 0;
            cout << "Pixel >200 :" << x << "," << y << endl;
        }
        else
        {
            color.val[0] = 255;
            color.val[1] = 255;
            color.val[2] = 255;
        }
    }
    imwrite("../images/imgopti"+to_string(i)+".tiff",image);

它似乎在輸出(使用 cout)中獲得了良好的像素,但是在輸出圖像(使用 imwrite)中,相關像素沒有被修改。 我已經嘗試過使用 color.val[0] .. 我仍然無法弄清楚為什么輸出圖像中的像素顏色沒有改變。 謝謝

除了將新像素值復制回圖像之外,您已完成所有操作。

此行將像素的副本復制到局部變量中:

Vec3b color = image.at<Vec3b>(Point(x,y));

因此,根據需要更改color后,只需將其設置回如下:

image.at<Vec3b>(Point(x,y)) = color;

所以,完整的,是這樣的:

Mat image = img;
for(int y=0;y<img.rows;y++)
{
    for(int x=0;x<img.cols;x++)
    {
        // get pixel
        Vec3b & color = image.at<Vec3b>(y,x);

        // ... do something to the color ....
        color[0] = 13;
        color[1] = 13;
        color[2] = 13;

        // set pixel
        //image.at<Vec3b>(Point(x,y)) = color;
        //if you copy value
    }
}

只需使用參考:

Vec3b & color = image.at<Vec3b>(y,x);
color[2] = 13;

出於性能原因,我不會使用 .at。

定義一個結構:

//#pragma pack(push, 2) //not useful (see comments below)
struct BGR {
    uchar blue;
    uchar green;
    uchar red;  };

然后在你的 cv::Mat 圖像上像這樣使用它:

BGR& bgr = image.ptr<BGR>(y)[x];

image.ptr(y) 給你一個指向掃描線 y 的指針。 並使用 x 和 y 循環遍歷像素

暫無
暫無

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

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