常用的图像像素遍历的三种方式有:
- 指针访问
- 迭代器iterator
- 动态地址at
#include <iostream>
#include <opencv2/opencv.hpp>
#include <cmath>
using namespace std;
using namespace cv;
//指针访问
void pointPixel(Mat &src, Mat &dst, int x);
//迭代器iterator
void iteratorPixel(Mat &src, Mat &dst, int x);
//动态地址at
void atPixel(Mat &src, Mat &dst, int x);
int main()
{
Mat input = imread("D:/opencv_coding/opencv_8.jpg");
imshow("the input image.", input);
Mat output;
pointPixel(input, output, 3);
//pointPixel(input, output, 3);
//atPixel(input, output, 3);
imshow("the output image.", output);
waitKey();
system("pause");
return 0;
}
void pointPixel(Mat &src, Mat &dst, int x)
{
dst = src.clone();
int rows = dst.rows;
int cols = dst.cols * dst.channels();
for (int i = 0; i < rows; i++)
{
uchar *data = dst.ptr<uchar>(i);
for (int j = 0; j < cols; j++)
{
data[j] = data[j] / (x*x) + x / 2;
}
}
}
void iteratorPixel(Mat &src, Mat &dst, int x)
{
dst = src.clone();
Mat_<Vec3b>::iterator it = dst.begin<Vec3b>();
Mat_<Vec3b>::iterator itend = dst.end<Vec3b>();
for (; it != itend; ++it)
{
(*it)[0] = (*it)[0] / (x*x) + x / 2;
(*it)[1] = (*it)[1] / (x*x) + x / 2;
(*it)[2] = (*it)[2] / (x*x) + x / 2;
}
}
void atPixel(Mat &src, Mat &dst, int x)
{
dst = src.clone();
int rows = dst.rows;
int cols = dst.cols;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
dst.at<Vec3b>(i, j)[0] = dst.at<Vec3b>(i, j)[0] / (x*x) + x / 2;
dst.at<Vec3b>(i, j)[1] = dst.at<Vec3b>(i, j)[1] / (x*x) + x / 2;
dst.at<Vec3b>(i, j)[2] = dst.at<Vec3b>(i, j)[2] / (x*x) + x / 2;
}
}
}