反色处理指的是:如果原先图像的背景是白色,而目标是黑色的话;经过反色处理后,背景变为白色,目标变为黑色。
在opencv中,对于二值图的反色处理有两种方法:
之前处理好的二值图的定义为:Mat binaryImg;
1、直接使用opencv中的函数:
//! inverts each bit of array (dst = ~src)
CV_EXPORTS_W void bitwise_not(InputArray src, OutputArray dst,
InputArray mask=noArray());
2、自己编写代码:
计算原理是 255-bin(x,y),代码如下:
Mat newBImg(binaryImg.rows, binaryImg.cols, binaryImg.type());
uchar* newBImgData = newBImg.data;
uchar* binaryData = binaryImg.data;
int step = binaryImg.step/sizeof(uchar);
for (int i=0; i<binaryImg.rows; i++)
{
for (int j=0;j<binaryImg.cols; j++)
{
newBImgData[i*step+j] = 255- binaryData[i*step+j];
}
}
binaryImg = newBImg.clone();