如何确定 OpenCV 中的像素是黑色还是白色

How do I determine if a pixel is black or white in OpenCV?

本文关键字:黑色 白色 像素 何确定 OpenCV      更新时间:2023-10-16

我在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++像素是黑色还是白色?

您可以将

at()函数用于Mat对象(请参阅 OpenCV 文档)。

img_otsu.at<uchar>(y,x)将返回矩阵中该位置的元素值。请注意,您可能需要将uchar更改为img_otsu的任何类型的矩阵(例如,floatdouble)。获得值后,只需将其与 0 或 255 进行比较即可。