如何在OpenCV中判断一个像素是黑色还是白色?
我有一段Python代码:
width = cv.GetSize(img_otsu)[0]
height = cv.GetSize(img_otsu)[1]
#print width,":",height
for y in range(height):
for x in range(width):
if(img_otsu[y,x]==(255.0)):
CountPixelW+=1
if(img_otsu[y,x]==(0.0)):
CountPixelB+=1
我想把这段Python代码转换成C++。
这是我目前的进展:
cv::threshold(img_gray,img_otsu,0.0,255.0,cv::THRESH_BINARY+cv::THRESH_OTSU);
for(int y =0;y<=img_otsu.size().height;y++)
for(int x=0;x<=img_otsu.size().width;x++)
{
//Check Pixel 0 or 255 This is Problem
}
我该如何在C++中检查一个像素是黑色还是白色呢?
1 个回答
0
你可以使用 at()
这个函数来操作 Mat
对象(具体可以参考 OpenCV 文档)。
比如,img_otsu.at<uchar>(y,x)
这个代码会返回矩阵中指定位置的值。需要注意的是,你可能需要把 uchar
改成 img_otsu
矩阵实际的类型(比如 float
或 double
)。拿到值后,你只需把它和 0 或 255 比较一下就行了。