opencv学习日记——图像添加椒盐噪声
1、图像结果
2、代码部分
#include<iostream>
#include<opencv2/opencv.hpp>
using namespace std;
using namespace cv;
void saltandpepper(Mat image, int n)
{
for (int k = 0; k < n / 2; k++)
{
int i, j;
i = rand() % image.cols;
j = rand() % image.rows;
int white_black = rand() % 2;
if (white_black == 0)
{
if (image.type() == CV_8UC1)
image.at<uchar>(j, i) = 255;
if (image.type() == CV_8UC3)
image.at<Vec3b>(j, i)[0] = 255;
image.at<Vec3b>(j, i)[1] = 255;
image.at<Vec3b>(j, i)[2] = 255;
}
if (white_black)
{
if (image.type() == CV_8UC1)
image.at<uchar>(j, i) = 0;
if (image.type() == CV_8UC3)
image.at<Vec3b>(j, i)[0] = 0;
image.at<Vec3b>(j, i)[1] = 0;
image.at<Vec3b>(j, i)[2] = 0;
}
}
}
int main()
{
Mat img = imread("reba.png");
Mat gray = imread("reba.png", IMREAD_ANYDEPTH);
imshow("img", img);
imshow("gray", gray);
saltandpepper(img, 10000);
saltandpepper(gray, 10000);
imshow("加噪声img", img);
imshow("加噪声gray", gray);
waitKey(0);
return -1;
}