#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <vector>
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 write_black = rand() % 2; //判定为白色噪声还是黑色噪声的变量
if (write_black == 0) //添加白色噪声
{
if (image.type() == CV_8UC1) //处理灰度图像
{
image.at<uchar>(j, i) = 255; //白色噪声
}
else if (image.type() == CV_8UC3) //处理彩色图像
{
image.at< Vec3b>(j, i)[0] = 255; //Vec3b为opencv定义的3个值的向量类型
image.at<Vec3b>(j, i)[1] = 255; //[]指定通道,B:0,G:1,R:2
image.at<Vec3b>(j, i)[2] = 255;
}
}
else //添加黑色噪声
{
if (image.type() == CV_8UC1)
{
image.at<uchar>(j, i) = 0;
}
else if (image.type() == CV_8UC3)
{
image.at<Vec3b>(j, i)[0] = 0; //Vec3b为opencv定义的3个值的向量类型
image.at<Vec3b>(j, i)[1] = 0; //[]指定通道,B:0,G:1,R:2
image.at<Vec3b>(j, i)[2] = 0;
}
}
}
}
int main()
{
Mat img = imread("D:\\Users\\59723\\Desktop\\lena.jpg", IMREAD_COLOR);
imshow("origin", img);
saltAndPepper(img, 10000);
//Mat element = getStructuringElement(MORPH_RECT, Size(2, 2));
//Mat dst;
//erode(img, dst, element);
//dilate(img, dst, element);
//morphologyEx(img, dst, MORPH_TOPHAT, element);
imshow("did", img);
waitKey(0);
destroyAllWindows();
}
重点:
i = rand() % image.cols; //取余数运算,保证在图像的列数内
j = rand() % image.rows; //取余数运算,保证在图像的行数内
rand()函数是C++中的随机数生成函数,它返回一个伪随机整数。使用%运算符对rand()函数返回的随机整数进行取余数运算,可以将其限制在一个特定的范围内。
通过rand() % image.cols可以生成一个在0到image.cols-1之间的随机整数,保证它在图像的列数范围内。
同样地,rand() % image.rows可以生成一个在0到image.rows-1之间的随机整数,保证它在图像的行数范围内。