一、椒盐噪声
? ?椒盐噪声是数字图像中的常见噪声,一般是图像传感器、传输信道及解码处理等产生的黑白相间的亮暗点噪声,椒盐噪声常由图像切割产生。椒盐噪声是指两种噪声:盐噪声和椒噪声。盐噪声一般是白色噪声,椒噪声一般为黑色噪声。前者属于高灰度噪声,或者属于低灰度噪声,一般两种噪声同时出现,呈现黑白杂点。去除椒盐噪声常用的方法是中值滤波。
二、C++代码
#include <opencv2\opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
void saltAndPepper(cv::Mat image, int n)
{
for (int k = 0; k < n / 2; k++)
{
int i, j;
i = std::rand() % image.cols;
j = std::rand() % image.rows;
int write_black = std::rand() % 2;
if (write_black == 0)
{
image.at<cv::Vec3b>(j, i)[0] = 255;
image.at<cv::Vec3b>(j, i)[1] = 255;
image.at<cv::Vec3b>(j, i)[2] = 255;
}
else
{
image.at<cv::Vec3b>(j, i)[0] = 0;
image.at<cv::Vec3b>(j, i)[1] = 0;
image.at<cv::Vec3b>(j, i)[2] = 0;
}
}
}
int main()
{
Mat lena = imread("qq.jpg");
if (lena.empty())
{
cout << "请确认图像文件名称是否正确" << endl;
return -1;
}
imshow("原图", lena);
saltAndPepper(lena, 10000);
imshow("添加噪声", lena);
waitKey(0);
return 0;
}
三、结果展示
1、原图
2、添加椒盐噪声
四、python代码
import numpy as np
import cv2
def salt_pepper_noise(image, prob):
"""
添加椒盐噪声
:param image: 输入图像
:param prob: 噪声比
:return: 带有椒盐噪声的图像
"""
salt = np.zeros(image.shape, np.uint8)
thres = 1 - prob
for i in range(image.shape[0]):
for j in range(image.shape[1]):
rdn = np.random.rand()
if rdn < prob:
salt[i][j] = 0
elif rdn > thres:
salt[i][j] = 255
else:
salt[i][j] = image[i][j]
return salt
src = cv2.imread('qq.jpg')
cv2.namedWindow('input_image', cv2.WINDOW_AUTOSIZE)
cv2.imshow('input_image', src)
tar = salt_pepper_noise(src, 0.01)
cv2.imshow('noise', tar)
cv2.waitKey(0)
cv2.destroyAllWindows()
五、结果展示
1、原图
2、添加椒盐噪声
|