fanfuhan OpenCV 教學024 ~ opencv-024-圖像增加雜訊

fanfuhan OpenCV 教學024 ~ opencv-024-圖像增加雜訊

fanfuhan OpenCV 教學024 ~ opencv-024-圖像增加雜訊


資料來源: https://fanfuhan.github.io/

https://fanfuhan.github.io/2019/04/03/opencv-024/

GITHUB:https://github.com/jash-git/fanfuhan_ML_OpenCV


C++

#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

void add_salt_pepper_noise(Mat &image);

void add_gaussian_noise(Mat &image);

/*
 * 噪声生成
 */
int main() {
    Mat src = imread("../images/test.png");
    Mat src_clone = src.clone();
    if (src.empty()) {
        cout << "could not load image.." << endl;
    }
    //imshow("input", src);

    // 产生椒盐噪声
    add_salt_pepper_noise(src_clone);
    // 产生高斯噪声
    add_gaussian_noise(src);

    waitKey(0);
    return 0;
}

void add_gaussian_noise(Mat &image) {
    Mat noise = Mat::zeros(image.size(), image.type());
    // 产生高斯噪声
    randn(noise, (15,15,15), (30,30,30));
    Mat dst;
    add(image, noise, dst);
    imshow("gaussian_noise", dst);
}

void add_salt_pepper_noise(Mat &image) {
    // 随机数产生器
    RNG rng(12345);
    for (int i = 0; i < 1000; ++i) {
        int x = rng.uniform(0, image.rows);
        int y = rng.uniform(0, image.cols);
        if (i % 2 == 1) {
            image.at<Vec3b>(y, x) = Vec3b(255, 255, 255);
        } else {
            image.at<Vec3b>(y, x) = Vec3b(0, 0, 0);
        }
    }
    imshow("saltp_epper", image);
}

Python

import cv2 as cv
import numpy as np


def add_salt_pepper_noise(image):
    h, w = image.shape[:2]
    nums = 10000
    rows = np.random.randint(0, h, nums, dtype=np.int)
    cols = np.random.randint(0, w, nums, dtype=np.int)
    for i in range(nums):
        if i % 2 == 1:
            image[rows[i], cols[i]] = (255, 255, 255)
        else:
            image[rows[i], cols[i]] = (0, 0, 0)
    return image


def gaussian_noise(image):
    noise = np.zeros(image.shape, image.dtype)
    m = (15, 15, 15)
    s = (30, 30, 30)
    cv.randn(noise, m, s)
    dst = cv.add(image, noise)
    cv.imshow("gaussian noise", dst)
    return dst


src = cv.imread("D:/vcprojects/images/cos.jpg")
h, w = src.shape[:2]
copy = np.copy(src)
copy = add_salt_pepper_noise(copy)

result = np.zeros([h, w*2, 3], dtype=src.dtype)
result[0:h,0:w,:] = src
result[0:h,w:2*w,:] = copy
cv.putText(result, "original image", (10, 30), cv.FONT_HERSHEY_PLAIN, 2.0, (0, 255, 255), 1)
cv.putText(result, "salt pepper image", (w+10, 30), cv.FONT_HERSHEY_PLAIN, 2.0, (0, 255, 255), 1)
cv.imshow("salt pepper noise", result)
cv.imwrite("D:/result.png", result)

cv.waitKey(0)
cv.destroyAllWindows()

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *