首页 > 技术文章 > CV中的日常操作

yuganwj 2020-08-19 19:38 原文

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()


 

推荐阅读