//为图像添加椒盐噪声
#include <stdio.h>
#include <iostream>
#include <string>
#include <opencv2\opencv.hpp>
using namespace std;
using namespace cv;
void add_salt(Mat & img);
int main()
{
//椒盐噪声,顾名思义就是在图像上撒上白色的盐和黑色的小黑椒
Mat img = imread("person3.jpeg");//读取的是三通道图像
namedWindow("原图", WINDOW_NORMAL);
imshow("原图", img);
for (int i = 0; i < img.cols*img.rows / 10; i++)
{
add_salt(img);
}
namedWindow("椒盐图", WINDOW_NORMAL);
imshow("椒盐图", img);
waitKey(0);
return 0;
}
void add_salt(Mat & img)
{
int x = std::rand() % img.cols;//得到增加噪点的列位置
int y = std::rand() % img.rows;//得到增加噪点的行位置
int select = std::rand() % 100;//与50比较用于决定是撒盐还是撒黑椒
if (img.channels() == 3)
{
if (select >= 50)//撒盐
{
img.at<Vec3b>(y, x)[0] = 255;
img.at<Vec3b>(y, x)[1] = 255;
img.at<Vec3b>(y, x)[2] = 255;
}
else//撒黑椒
{
img.at<Vec3b>(y, x)[0] = 0;
img.at<Vec3b>(y, x)[1] = 0;
img.at<Vec3b>(y, x)[2] = 0;
}
}
else//灰度图
{
if (select >= 50)//撒盐
{
img.at<float>(y, x) = 255;
}
else//撒黑椒
{
img.at<float>(y, x) = 0;
}
}
}
初识Opencv4.X----为图像添加椒盐噪声
猜你喜欢
转载自blog.csdn.net/qq_46146657/article/details/120317009
今日推荐
周排行