CV中的日常操作
阿新 • • 發佈:2020-08-19
1.過濾圖片中的噪聲
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('./01.jpg', 0) # 直接讀取為灰度影象
img1 = cv2.imread('./01.jpg', 1)
for i in range(2000):
temp_x = np.random.randint(0, img.shape[0])
temp_y = np.random.randint(0, img.shape[1])
img[temp_x][temp_y] = 255
img1[temp_x][temp_y] = 255
blur11 = cv2.GaussianBlur(img, (5, 5), 0) # 高斯濾波
blur21 = cv2.medianBlur(img, 5) # 中指濾波
blur12 = cv2.GaussianBlur(img1, (5, 5), 0)
blur22 = cv2.medianBlur(img1, 5)
plt.subplot(2, 3, 1)
plt.imshow(img, 'gray') # 預設顏色,另一種為'bgr'
plt.subplot(2, 3, 2)
plt.imshow(blur11, 'gray') # 預設顏色,另一種為'bgr'
plt.subplot(2, 3, 3)plt.imshow(blur21, 'gray') # 預設顏色,另一種為'bgr'
plt.subplot(2, 3, 4)
plt.imshow(img1, 'brg')
plt.subplot(2, 3, 5)
plt.imshow(blur12, 'brg')
plt.subplot(2, 3, 6)
plt.imshow(blur22, 'brg')
plt.show()
2.邊緣檢測
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
img = cv.imread('./02.jpg', 0)
laplacian = cv.Laplacian(img, cv.CV_64F) # 拉普拉斯運算元sobelx = cv.Sobel(img, cv.CV_64F, 1, 0, ksize=5) # sobel運算元是一種常用的邊緣檢測運算元
sobely = cv.Sobel(img, cv.CV_64F, 0, 1, ksize=5)
plt.subplot(2, 2, 1)
plt.imshow(img, cmap='gray')
plt.title('Original')
plt.xticks([])
plt.yticks([])
plt.subplot(2, 2, 2)
plt.imshow(laplacian, cmap='gray')
plt.title('Laplacian')
plt.xticks([])
plt.yticks([])
plt.subplot(2, 2, 3)
plt.imshow(sobelx, cmap='gray')
plt.title('SabelX')
plt.xticks([])
plt.yticks([])
plt.subplot(2, 2, 4)
plt.imshow(sobely, cmap='gray')
plt.title('SabelY')
plt.xticks([])
plt.yticks([])
plt.show()
3.快速傅立葉變化
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 快速傅立葉變換 時空=> 頻率
img = cv2.imread('./02.jpg', 0)
f = np.fft.fft2(img)
fshift = np.fft.fftshift(f)
megnitude_spectrun = 20 * np.log(np.abs(fshift))
plt.subplot(1, 2, 1)
plt.imshow(img, cmap='gray')
plt.title('Inpute Image')
plt.xticks()
plt.yticks()
plt.subplot(1, 2, 2)
plt.imshow(megnitude_spectrun, cmap='gray')
plt.title('Output Image')
plt.xticks()
plt.yticks()
plt.show()
4.圖片直方圖均衡化
import numpy as np
import matplotlib.pyplot as plt
import cv2
img = cv2.imread('./03.jpg', 0)
res = cv2.equalizeHist(img) # 直方圖均衡化
clahe = cv2.createCLAHE(clipLimit=2, tileGridSize=(10, 10)) # 生成自適應均衡化影象
cl1 = clahe.apply(img)
plt.subplot(1, 3, 1)
plt.imshow(img, 'gray')
plt.subplot(1, 3, 2)
plt.imshow(res, 'gray')
plt.subplot(1, 3, 3)
plt.imshow(cl1, 'gray')
plt.show()