#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
//1,最快方式,利用 C[]
Mat src = imread("D:/Code/image/1.jpg");
Mat dst = src.clone();
int rowNum = dst.rows;
int colNum = dst.cols * dst.channels();
int divideWidth = 50; //颜色间隔大小
imshow("输入图像", src);
for (int i = 0; i < rowNum; i++)
{
uchar* data = dst.ptr<uchar>(i); // 获取第i行的首地址
for (int j = 0; j < colNum; j++)
{
data[j] = data[j] / divideWidth * divideWidth + divideWidth / 2; //处理每个像素方式
}
}
imshow("效果图", dst);
waitKey(6000);
return 0;
}
//2,最简洁方式,利用动态地址运算配合at方法
for (int i = 0; i < dst.rows; i++)
{
for (int j = 0; j < dst.cols; j++)
{
dst.at<Vec3b>(i, j)[0] = dst.at<Vec3b>(i, j)[0] / divideWidth * divideWidth + divideWidth / 2;
dst.at<Vec3b>(i, j)[1] = dst.at<Vec3b>(i, j)[1] / divideWidth * divideWidth + divideWidth / 2;
dst.at<Vec3b>(i, j)[2] = dst.at<Vec3b>(i, j)[2] / divideWidth * divideWidth + divideWidth / 2;
}
}
上面是彩色图访问方式,下面介绍灰度的访问方式:
Mat img = imread("D:/Code/Image/classic.jpg", 0); //以灰度图形式读入
imshow("原图", img);
//1,快,和彩色图一样,只不过像素的个数少了三倍
for (int i = 0; i < img.rows; i++)
{
uchar *p = img.ptr<uchar>(i);
for (int j = 0; j < img.cols; j++)
{
if (p[j] > 150)
p[j] = 255;
else
p[j] = 0;
}
}
//2,简
/*for (int i = 0; i < img.rows; i++)
for (int j = 0; j < img.cols; j++)
{
if (img.at<uchar>(i, j) > 150)
img.at<uchar>(i, j) = 255;
else
img.at<uchar>(i, j) = 0;
}*/
imshow("二值化后", img);