Image Noise (OpenCV)

Table of contents

1. The principle of artificially adding noise to the image

2. Python code

3. Example picture

Fourth, the operation effect diagram:

5. The meaning of adding noise        


1. The principle of artificially adding noise to the image

        Set the value of several pixel points of the image to the value of the noise point. For example, to add a lot of pixel points with pixel values ​​[25,20,20] to the image, write the code as follows:

 for k in range(coutn):
        # Obtain the random position of image noise points
        i = int(np.random.uniform(0, img.shape[1]))
        j = int(np.random.uniform(0, img. shape[0]))
            #image plus noise point
        if img.ndim == 2:
            img[j,i] = 255
        elif img.ndim == 3:
            img[j,i,0] = 25
            img[j,i ,1] = 20
            img[j,i,2] = 20

        The purpose of the above code to judge img.ndim is that if the image is a grayscale image, then img.ndim is 2, and the pixel values ​​of the grayscale image do not have red, green, and blue colors, only gray degree value, so only one pixel value is needed, and the value corresponding to the position of the noise point is set to 255.

2. Python code

        The following code demonstrates the algorithm for adding noise to the image, artificially adding 500,000 pixels of random color to the color image.

import cv2
import numpy as np

fn = r"C:\Users\LIHAO\Pictures\Saved Pictures\wallhaven-gpqzr3.png"
if __name__ == '__main__':
    # 加载图像
    img = cv2.imread(fn)
    # 噪声点数量
    coutn = 500000
    for k in range(coutn):
        # 获取图像噪声点的随机位置
        i = int(np.random.uniform(0, img.shape[1]))
        j = int(np.random.uniform(0, img.shape[0]))
            #图像加噪声点
        if img.ndim == 2:
            img[j,i] = 255
        elif img.ndim == 3:
            img[j,i,0] = 25
            img[j,i,1] = 20
            img[j,i,2] = 20
    cv2.namedWindow('img')
    cv2.imshow('img',img)
    cv2.waitKey()
    cv2.destroyAllWindows()

3. Example picture

Fourth, the operation effect diagram:

        The operation principle of the above program is to set the pixel at the random position of the image data matrix to (25, 20, 20). When the random pixel is large, noise is generated on the image.

5. The meaning of adding noise        

        Adding noise to the image is to test the effect of image recognition. Some machine learning algorithms have a good effect on image recognition without noise. In the application, it is difficult to ensure that the collected images are clear and reliable, so it is necessary to artificially add noise to the image in order to verify the effect of the algorithm later.

Guess you like

Origin blog.csdn.net/weixin_51756038/article/details/130047227