数字图像处理c++ opencv(VS2019 opencv4.53)持续更新
以8位(0~255)灰度图像和BGR彩色图像为例,用at可以访问图像像素:
//灰度图像:
image.at<uchar>(j, i) //j为行数,i为列数
//BGR彩色图像
image.at<Vec3b>(j, i)[0] //B分量
image.at<Vec3b>(j, i)[1] //G分量
image.at<Vec3b>(j, i)[2] //R分量
1.创建Salt头文件
#pragma once
#include
#include
#include //随机数头文件
using namespace cv;
using namespace std;
void Salt(Mat image, int n); //n:加入噪声点数
2.创建Salt源文件
#include "Salt.h"
void Salt(Mat image, int n)
{
//随机数生成器
default_random_engine generater;
uniform_int_distribution<int>randomRow(0, image.rows - 1);
uniform_int_distribution<int>randomCol(0, image.cols - 1);
int i, j;
for (int k = 0; k < n; k++)
{
i = randomCol(generater);
j = randomRow(generater);
if (image.channels() == 1)
{
image.at<uchar>(j, i) = 255;
}
else if (image.channels() == 3)
{
image.at<Vec3b>(j, i)[0] = 255;
image.at<Vec3b>(j, i)[1] = 255;
image.at<Vec3b>(j, i)[2] = 255;
}
}
}
3.示例
#include
#include
#include "Salt.h"
using namespace cv;
using namespace std;
int main()
{
Mat image1 = imread("lena.png"); //读取图像;
if (image1.empty())
{
cout << "读取错误" << endl;
return -1;
}
imshow("image1", image1); //显示原图像;
Salt(image1, 5000); //加入5000个噪声点
imshow("image2", image1); //显示噪声图像;
waitKey(0); //暂停,保持图像显示,等待按键结束
return 0;
}
#include
#include
using namespace cv;
using namespace std;
int main()
{
Mat image1, output_image; //定义输入图像和输出图像
image1 = imread("lena.png"); //读取图像;
if (image1.empty())
{
cout << "读取错误" << endl;
return -1;
}
output_image = Mat(image1.size(), image1.type()); //定义输出图像大小
output_image = image1.clone(); //克隆原图像素值
int rows = image1.rows; //原图行数
int stepx = image1.channels(); //原图通道数
int cols = (image1.cols) * image1.channels(); //矩阵总列数,在BGR彩色图像中,每个像素的BGR通道按顺序排列,因此总列数=像素宽度*通道数
for (int row =1 ; row < (rows - 1); row++) //对行遍历
{
const uchar* previous = image1.ptr<uchar>(row - 1); //原图上一行指针
const uchar* current = image1.ptr<uchar>(row); //原图当前行指针
const uchar* next = image1.ptr<uchar>(row + 1); //原图下一行指针
uchar* output = output_image.ptr<uchar>(row); //输出图像当前行指针
for (int col = stepx; col < (cols- stepx); col++) //对列遍历
{
output[col] = saturate_cast<uchar>(5*current[col] - (previous[col]+ current[col- stepx]+ current[col + stepx]+ next[col]));
//saturate_cast(a),当a在0—255时输出a,当a小于0输出0,当a大于255输出255,保证a的值在0~255之间
}
}
imshow("image1", image1);
imshow("output_image", output_image);
waitKey(0); //暂停,保持图像显示,等待按键结束
return 0;
}
结果:
上面的方法可以简化为:
#include
#include
using namespace cv;
using namespace std;
int main()
{
Mat image1, output_image; //定义输入图像和输出图像
image1 = imread("lena.png"); //读取图像;
if (image1.empty())
{
cout << "读取错误" << endl;
return -1;
}
Mat kernel = (Mat_<char>(3,3) << 0, -1, 0, -1, 5, -1, 0, -1, 0); //创建滤波器
filter2D(image1, output_image, image1.depth(), kernel); //卷积
imshow("image1", image1);
imshow("output_image", output_image);
waitKey(0); //暂停,保持图像显示,等待按键结束
return 0;
}