在opencv中,如何把灰度图像中的黑和白快速转化为1和0;

2025-03-24 23:54:35
推荐回答(2个)
回答1:

应该是先转成二值图再变成一和零的矩阵吧?

假定原图是src,输出图是dst

c++实现:

cv::threshold(src, dst, 255 / 2, 255, cv::THRESH_BINARY); 
dst /= 255;

python实现:

dst = cv2.threshold(src, 255 / 2, 255, cv2.THRESH_BINARY)
dst /= 255

回答2:

for(int i=0;i <= img->height;i++)
{
for(int j=0;j <= img->width;j++)
{
if(img->imageData[img->height*i+j] == 0)
{
img->imageData[img->height*i+j] = 1;
}
else if(img->imageData[img->height*i+j] == 255)
{
img->imageData[img->height*i+j] = 0;
}
}
}

img是你的图像,黑色像素值为0变为1,白色像素值为255变为0,用for遍历一下图像的每个像素点就行。