利用动态地址进行访问
Mat srcImage(100, 100, CV_8UC3, Scalar(200,20,100));
int rowNumber = srcImage.rows;
int colNumber = srcImage.cols;
for (int i = 0; i < rowNumber; i++)
{
for (int j = 0; j < colNumber; j++)
{
if (srcImage.at<Vec3b>(i, j)[0] > 180)
{
srcImage.at<Vec3b>(i, j)[0] = 0;
}
if (srcImage.at<Vec3b>(i, j)[1] < 50)
{
srcImage.at<Vec3b>(i, j)[1] = 255;
}
if (srcImage.at<Vec3b>(i, j)[2] < 120)
{
srcImage.at<Vec3b>(i, j)[2] = 0;
}
}
}
利用指针进行访问
方法一
void colorReduce(Mat& inputImage, Mat& outputImage, int div)
{
outputImage = inputImage.clone();
int rowNumber = outputImage.rows;
int colNumber = outputImage.cols*outputImage.channels();
for (int i = 0; i < rowNumber; i++)
{
uchar* data = outputImage.ptr<uchar>(i);
for (int j = 0; j < colNumber; j++)
{
data[j] = data[j] - div;
}
}
}
方法二
Mat inverseColor1(Mat srcImage)
{
Mat tempImage = srcImage.clone();
int row = tempImage.rows;
int col = tempImage.cols * tempImage.channels();
for (int i = 0; i < row; ++i)
{
const unsigned char* sourcedata = srcImage.ptr(i);
unsigned char* data = tempImage.ptr(i);
for (int j = 0; j < col; j++)
{
data[j] = sourcedata[j] - div;
}
}
return tempImage;
}
注意
Mat 除了拥有成员变量cols,rows,成员函数channels()之外,还提供了ptr函数可以返回得到图像任意行的首地址。
利用迭代器进行访问
Mat inverseColor4(Mat srcImage)
{
Mat tempImage = srcImage.clone();
MatConstIterator_<Vec3b> srcIterStart = srcImage.begin<Vec3b>();
MatConstIterator_<Vec3b> srcIterEnd = srcImage.end<Vec3b>();
MatIterator_<Vec3b> resIterStart = tempImage.begin<Vec3b>();
MatIterator_<Vec3b> resIterEnd = tempImage.end<Vec3b>();
while (srcIterStart != srcIterEnd)
{
(*resIterStart)[0] = 255 - (*srcIterStart)[0];
(*resIterStart)[1] = 255 - (*srcIterStart)[1];
(*resIterStart)[2] = 255 - (*srcIterStart)[2];
srcIterStart++;
resIterStart++;
}
return tempImage;
}