在进行图像检测或识别之前,都需要对原始图像进行图像预处理。笔者在此简单描述在图像像素相加过程的认识。图形像素相加是对图像的一种简单降噪过程。其次,我们知道一幅图像在数学计算过程中,其实就是一个二维矩阵,那么图像的像素相加也就是各个对应点的求和。这就要求我们运算的两幅图像的维度必须相同,行和列必须对应相等,否则无法继续,首先我是使用opencv 自带的函数API进行求解,然后通过数学的方式再次进行计算,加深对该运算的理解。
使用API的运行过程:
#include <opencv2/opencv.hpp>
#include <stdio.h>
#include <stdlib.h>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
Mat Image_1 = imread("D://Image//5039.jpg"); //读取一幅图像
Mat Image_2 = imread("D://Image//5041.jpg"); //读取相同的另一幅图像
namedWindow("图1", WINDOW_AUTOSIZE);
namedWindow("图2", WINDOW_AUTOSIZE);
imshow("图1",Image_1);
imshow("图2",Image_2);
int Image_1_cols = Image_1.cols;
int Image_1_rows = Image_1.rows;
int Image_2_cols = Image_2.cols;
int Image_2_rows = Image_2.rows;
cout << "Image_1_ cols:" << Image_1_cols <<" "<<"Image_2_ cols:"<< Image_2_cols << endl;
cout << "Image_1_ rows:" << Image_1_rows <<" "<<"Image_2_ rows:"<< Image_2_rows <<endl;
Mat dst;
//dst = Image_1 + Image_2; //两种方式都可以实现
add(Image_1, Image_2, dst);
namedWindow("求和1", WINDOW_AUTOSIZE);
imshow("求和1", dst);
waitKey();
return 1;
}
运行结果如下:
使用指针访问像素进行加法运算:
#include <opencv2/opencv.hpp>
#include <stdio.h>
#include <stdlib.h>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
Mat Image_1 = imread("D://Image//5039.jpg"); //读取一幅图像
Mat Image_2 = imread("D://Image//5041.jpg"); //读取相同的另一幅图像
namedWindow("图1", WINDOW_AUTOSIZE);
namedWindow("图2", WINDOW_AUTOSIZE);
imshow("图1", Image_1);
imshow("图2", Image_2);
int Image_1_cols = Image_1.cols;
int Image_1_rows = Image_1.rows;
int Image_2_cols = Image_2.cols;
int Image_2_rows = Image_2.rows;
cout << "Image_1_ cols:" << Image_1_cols << " " << "Image_2_ cols:" << Image_2_cols << endl;
cout << "Image_1_ rows:" << Image_1_rows << " " << "Image_2_ rows:" << Image_2_rows << endl;
Mat dst;
dst.create(Image_1.size(), Image_1.type());
//dst = Image_1 + Image_2; //两种方式都可以实现
//add(Image_1, Image_2, dst);
int B1, B2, G1, G2, R1, R2;
for (int row = 0; row < Image_1_rows; row++)
{
for (int col = 0; col < Image_1_cols; col++)
{
int B1 = Image_1.at<Vec3b>(row, col)[0];
int G1 = Image_1.at<Vec3b>(row, col)[1];
int R1 = Image_1.at<Vec3b>(row, col)[2];
int B2 = Image_2.at<Vec3b>(row, col)[0];
int G2 = Image_2.at<Vec3b>(row, col)[1];
int R2 = Image_2.at<Vec3b>(row, col)[2];
dst.at<Vec3b>(row, col)[0] = saturate_cast<uchar>(B1 + B2);
dst.at<Vec3b>(row, col)[1] = saturate_cast<uchar>(G1 + G2);
dst.at<Vec3b>(row, col)[2] = saturate_cast<uchar>(R1 + R2);
}
}
namedWindow("求和2", WINDOW_AUTOSIZE);
imshow("求和2", dst);
waitKey(0);
return 1;
}
运行结果如下: