我创建了一个小程序,通过将图像转换为hsv来检测红色。为了检测红色,我使用最小范围170,160,160和最大范围180,255,255。因此,我得到了显示白色红色的hsv图像。现在我想知道那个白色像素的值。我知道x,y坐标。我该如何获取像素值?我正在使用Python和cv2。
我创建了一个小程序,通过将图像转换为hsv来检测红色。为了检测红色,我使用最小范围170,160,160和最大范围180,255,255。因此,我得到了显示白色红色的hsv图像。现在我想知道那个白色像素的值。我知道x,y坐标。我该如何获取像素值?我正在使用Python和cv2。
所以你已经有了x和y,
-> 只需创建大小为1X1的ROI矩阵
-> 使用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();
}
@user3352710 @Pe Dro,这在Python中非常容易实现。以下是简单的代码。
def coords_mouse_disp(event,x,y,flags,param):
if event == cv2.EVENT_LBUTTONDBLCLK: #left mouse double click
print("Orginal BGR:",img[x,y])
print("HSV values:", HSV[x,y])
path = "your_image_path.png"
while True:
img = cv2.imread(path)
#img = cv2.resize(img, None, fx=0.5, fy=0.5)
HSV = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
cv2.imshow("Original",img)
cv2.imshow("HSV", HSV)
#left mouse click event
cv2.setMouseCallback("HSV", coords_mouse_disp)
cv2.setMouseCallback("Original", coords_mouse_disp)
if cv2.waitKey(1) &0xFF == ord("q"):
cv2.destroyAllWindows()
break
print("原始BGR:",img[y,x]);print("HSV值:", HSV[y,x]);
- Qua285