gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
add gaussian noise in gray img in python by cv2
- User
add gaussian noise in gray img in python by cv2
- Assistant
To add Gaussian noise to a gray image in Python using OpenCV (cv2), you can follow the steps below:
import cv2 import numpy as np # Load the image in grayscale img = cv2.imread('gray_image.jpg', cv2.IMREAD_GRAYSCALE) # Generate the Gaussian noise mean = 0 stddev = 50 noise = np.random.normal(mean, stddev, img.shape).astype(np.uint8) # Add the noise to the image noisy_img = cv2.add(img, noise) # Display the original and noisy images cv2.imshow('Original', img) cv2.imshow('Noisy', noisy_img) cv2.waitKey(0) cv2.destroyAllWindows()In the above code, we first load the grayscale image using
cv2.imreadwith the flagcv2.IMREAD_GRAYSCALE. Then, we usenp.random.normalto generate Gaussian noise with the specified mean and standard deviation. We convert the noise values touint8usingastypeto match the image datatype. Finally, we add the noise to the original image usingcv2.addto get the noisy image and display both images usingcv2.imshow.