Skip to content

Instantly share code, notes, and snippets.

@JustinSDK
Created May 24, 2021 04:17
Show Gist options
  • Save JustinSDK/184c519b258dcde9d3f38bb8c47e7d7d to your computer and use it in GitHub Desktop.
Save JustinSDK/184c519b258dcde9d3f38bb8c47e7d7d to your computer and use it in GitHub Desktop.
傅立葉轉換與雜訊分析
import cv2
import numpy as np
# 椒鹽雜訊
def salt_pepper_noise(image, fraction, salt_vs_pepper):
img = np.copy(image)
size = img.size
num_salt = np.ceil(fraction * size * salt_vs_pepper).astype('int')
num_pepper = np.ceil(fraction * size * (1 - salt_vs_pepper)).astype('int')
row, column = img.shape
x = np.random.randint(0, column - 1, num_pepper)
y = np.random.randint(0, row - 1, num_pepper)
img[y, x] = 0
x = np.random.randint(0, column - 1, num_salt)
y = np.random.randint(0, row - 1, num_salt)
img[y, x] = 255
return img
def fftshow(title, img):
f = np.fft.fft2(img)
shifted = np.fft.fftshift(f)
amp = np.abs(shifted)
fimg = amp / np.max(amp) * 255
cv2.imshow(title, fimg)
# 圖片來源:https://openhome.cc/Gossip/images/caterpillar.jpg
img = cv2.imread('caterpillar.jpg', cv2.IMREAD_GRAYSCALE)
cv2.imshow('caterpillar', img)
fftshow('caterpillar FFT', img)
noisy = salt_pepper_noise(img, 0.1 , 0.5)
cv2.imshow('noisy', noisy)
fftshow('Noisy FFT', noisy)
cv2.waitKey(0)
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment