python
import cv2 as cv
import numpy as np
def add_salt_pepper_noise(image):
h, w = image.shape[:2]
nums = 10000
row = np.random.randint(0, h, nums, dtype = np.int)
col = np.random.randint(0, w, nums, dtype = np.int)
for i in range(nums):
if i % 2 == 1:
image[row[i], col[i]] = [255, 255, 255]
else:
image[row[i], col[i]] = [0, 0, 0]
return image
def add_gaussian_noise(image):
noise = np.zeros(image.shape, image.dtype)
m = (15, 15, 15)#mean
n = (30, 30, 30)#stdDev
cv.randn(noise, m, n)
dst = cv.add(image, noise)
cv.imshow("gaussian_noise", noise)
return dst
img = cv.imread("../mm.jpg")
copy1 = np.copy(img)
copy2 = np.copy(img)
h, w = img.shape[:2]
result = np.zeros([h, w * 2, 3], dtype=img.dtype)
result1 = np.zeros([h, w * 2, 3], dtype=img.dtype)
dst = add_gaussian_noise(copy1)
dst1 = add_salt_pepper_noise(copy2)
result[:, : w, :] = img
result[:, w : 2 * w, :] = dst
result1[:, : w, :] = img
result1[:, w : 2 * w, :] = dst1
cv.putText(result, "origin image", (10, 30),
cv.FONT_HERSHEY_PLAIN, 2.0, (0, 255, 255), 1)
cv.putText(result, "add_gaussian_noise", (w + 10, 30),
cv.FONT_HERSHEY_PLAIN, 2.0, (0, 255, 255), 1)
cv.imshow("img_add_gaussian_noise", result)
cv.putText(result1, "origin image", (10, 30),
cv.FONT_HERSHEY_PLAIN, 2.0, (0, 255, 255), 1)
cv.putText(result1, "add_salt_pepper_noise", (w + 10, 30),
cv.FONT_HERSHEY_PLAIN, 2.0, (0, 255, 255), 1)
cv.imshow("img_add_salt_pepper_noise", result1)
cv.waitKey(0)
cv.destroyAllWindows()
python中新知识点:
- np.copy()
- cv.randn()
- cv.add()
- np.random.randint()
- cv.putText()
c++
#include "all.h"
using namespace std;
using namespace cv;
//void addGaussianNoise(Mat img);
void MyClass::day024() {
Mat img = myRead("mm.jpg");
Mat copy1 = img.clone();
Mat copy2 = img.clone();
//addGaussianNoise(copy1);
addSaltPepperNoise(copy2);
addGuassianNoise(copy1);
//imshow("GaussianNoise", copy1);
imshow("SaltPepper", copy2);
}
void MyClass::addSaltPepperNoise(Mat &img) {
RNG rng(12345);
int row = img.rows;
int col = img.cols;
int num = 10000;
for (int i = 0; i < num; i++) {
int x = rng.uniform(0, row);
int y = rng.uniform(0, col);
if (i % 2 == 1)
img.at<Vec3b>(x, y) = Vec3b(255, 255, 255);
else
img.at<Vec3b>(x, y) = Vec3b(0, 0, 0);
}
}
void MyClass::addGuassianNoise(Mat &img) {
Mat noise = Mat::zeros(img.size(), img.type());
randn(noise, (15, 15, 15), (30, 30, 30));
Mat dst;
add(img, noise, dst);
imshow("GuassianNoise", dst);
}
c++的新知识点:
- cv::RNG:随机数产生器
- cv::randn()
- cv::add()