我创建了一个小程序,通过将图像转换为hsv来检测红色。为了检测红色,我使用最小范围170,160,160和最大范围180,255,255。因此,我得到了hsv图像,该图像显示白色为红色。现在,我想知道该白色像素的值。我知道x,y坐标。如何获得像素值?我正在使用python和cv2。

最佳答案

所以你已经有了x和y

->只需创建1X1大小的ROI Mat

->使用CvtColor()转换HSV颜色空间

->访问上述结果的像素值

Mat image; //load image here
Mat HSV;
Mat RGB=image(Rect(x,y,1,1)); // use your x and y value

cvtColor(RGB, HSV,CV_BGR2HSV);
Vec3b hsv=HSV.at<Vec3b>(0,0);
int H=hsv.val[0]; //hue
int S=hsv.val[1]; //saturation
int V=hsv.val[2]; //value

您可以引用下面的C++代码,该代码将显示对应于鼠标位置的像素的RGB和HSV值。
char window_name[30] = "HSV Segmentation";
Mat src;

static void onMouse( int event, int x, int y, int f, void* ){
 Mat image=src.clone();
 Vec3b rgb=image.at<Vec3b>(y,x);
 int B=rgb.val[0];
 int G=rgb.val[1];
 int R=rgb.val[2];

  Mat HSV;
  Mat RGB=image(Rect(x,y,1,1));
  cvtColor(RGB, HSV,CV_BGR2HSV);

    Vec3b hsv=HSV.at<Vec3b>(0,0);
    int H=hsv.val[0];
    int S=hsv.val[1];
    int V=hsv.val[2];

    char name[30];
    sprintf(name,"B=%d",B);
    putText(image,name, Point(150,40) , FONT_HERSHEY_SIMPLEX, .7, Scalar(0,255,0), 2,8,false );

    sprintf(name,"G=%d",G);
    putText(image,name, Point(150,80) , FONT_HERSHEY_SIMPLEX, .7, Scalar(0,255,0), 2,8,false );

    sprintf(name,"R=%d",R);
    putText(image,name, Point(150,120) , FONT_HERSHEY_SIMPLEX, .7, Scalar(0,255,0), 2,8,false );

    sprintf(name,"H=%d",H);
    putText(image,name, Point(25,40) , FONT_HERSHEY_SIMPLEX, .7, Scalar(0,255,0), 2,8,false );

    sprintf(name,"S=%d",S);
    putText(image,name, Point(25,80) , FONT_HERSHEY_SIMPLEX, .7, Scalar(0,255,0), 2,8,false );

    sprintf(name,"V=%d",V);
    putText(image,name, Point(25,120) , FONT_HERSHEY_SIMPLEX, .7, Scalar(0,255,0), 2,8,false );

    sprintf(name,"X=%d",x);
    putText(image,name, Point(25,300) , FONT_HERSHEY_SIMPLEX, .7, Scalar(0,0,255), 2,8,false );

    sprintf(name,"Y=%d",y);
    putText(image,name, Point(25,340) , FONT_HERSHEY_SIMPLEX, .7, Scalar(0,0,255), 2,8,false );

 //imwrite("hsv.jpg",image);
 imshow( window_name, image );
}



int main(){
 src = imread("bgr.png",1);
 imshow(window_name,src);
 setMouseCallback( window_name, onMouse, 0 );
 waitKey();
 }

关于opencv - 转换为hsv后如何获取特定像素的值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22257477/

10-13 06:28