OpenCV (C++) - Set HSV values of a pixel

寵の児 提交于 2019-12-04 05:31:35

问题


I have an RGB image that i converted to HSV and my goal is to set every pixel that doesn't meet a certain hue value (100) to black. So H = S = V = 0.

I have this code: (frame3 is the HSV Mat image, hue = 100)

    for (int i = 0; i<frame3.rows; i++)   
    {
        for (int j = 0; j<frame3.cols; j++)
        {
            Vec3b hsv = frame3.at<Vec3b>(i, j);
            int H = hsv.val[0]; //hue
            int S = hsv.val[1]; //saturation
            int V = hsv.val[2]; //value
            if (H != hue) {
                H = 0;
                S = 0;
                V = 0;
            }

        }
    }
    imshow("Processed Hue", frame3);
}

But when i run it nothing happens..the image stays the same. When i tried printing out the hsv.val[0] values to the console, i got letters and not numbers.. so i think that kind of points to where the problem is but i still don't know how to fix it.

Any help would be greatly appreciated! Thanks!


回答1:


You can:

  • build a mask where H channel equals 100, regardless the values of S,V channels (with inRange)
  • set frame3 to zero according to the mask (with setTo)

Something like:

Mat frame3; // CV_8UC3, HSV image

Mat mask;
inRange(frame3, Scalar(100,0,0), Scalar(100, 255, 255), mask);

frame3.setTo(Scalar(0,0,0), mask);

To keep your code structure, you need to modify the actual value, not a copy of the value. You can do that keeping a reference to the value:

 Vec3b& hsv = frame3.at<Vec3b>(i, j);
 if (hsv[0] != hue) {
    hsv[0] = 0;
    hsv[1] = 0;
    hsv[2] = 0;
 }  


来源:https://stackoverflow.com/questions/35846581/opencv-c-set-hsv-values-of-a-pixel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!