環境:Anaconda 3.6
首先安裝cv2的包: pip3 install opencv-python
import cv2
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
def img_show(img_name, img):
cv2.imshow(img_name, img)
cv2.waitKey(0) ?# 只顯示第一幀
cv2.destroyAllWindows() ?# 銷毀所有的窗口
img_file = 'sudoku.png'
img = cv2.imread(img_file) # 已彩色模式讀取圖像文件
rows, cols, ch = img.shape # 獲取圖像形狀
img_show('raw img', img)
# 圖像縮放
img_scale = cv2.resize(img, None, fx=0.6, interpolation=cv2.INTER_CUBIC)
img_show('scale img', img_scale)
# 圖像平移
M = np.float32([[1,0,100],[0,1,50]]) # x=>100, y=>50
img_transform = cv2.warpAffine(img, M, (rows,cols)) # 平移圖像
img_show('transform img', img_transform)
# 圖像旋轉
M = cv2.getRotaionMatrix2D((cols/2, rows/2), 45, 0.6)
img_rotation = cv2.warpAffine(img, M, (cols, rows))
img_show('rotation img', img_rotation)
# 透視轉化
pst1 = np.float32([[x1,y1],[x2,y2], [x3,y3], [x4,y4]]) # 轉換前四個點坐標
pst2 = np.float32([[x5,y5],[x6,y6], [x7,y7], [x8,y8]]) # 轉換后四個點坐標
M = cv2.getPerspectiveTransform(pst1, pst2)
img_perspective = cv2.warpPerspective(img, M, (x,y))
img_show('perspective img', img_perspective)
# 轉化為灰度圖片
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 圖像轉灰色
img_show('gray img', gray_img)
# 邊緣檢測
edge_img = cv2.Canny(img, 50,100)
img_show('edge img', edge_img)
# 二值化處理
ret, th1 = cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY)
# 127為閥值,255為(超過或小于閥值)賦予的值,THRESH_BINARY類型
th2 = cv2.adaptive(gray_img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11,2)
#均值閥值,11=>圖像分塊數, 2=>計算閥值的常數項
th3 = cv2.adaptive(gray_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11,2) # 自適應高斯閥值
titles = ['GRAY_IMG', 'GLOBAL img', 'mean_img', 'gussian img']
imgs = [gray_img, th1, th2, th3]
for i in range(4):
plt.subplot(2,2, i+1),plt.imshow(imgs[i], 'gray')? # 以灰度模式展開各個子網格
plt.title(titles[i])?
plt.xticks([]), plt.yticks([]) # 設置坐標顯示值
plt.suptitle('img') # 表頭
plt.show() # 顯示圖像
# 圖像平滑
kernel = np.ones((5,5), np.float32) /25 # 設置平滑內核大小
img_smoth_filter2D = cv2.filter2D(img, -1, kernel) # 2D 卷積法
img_smoth_blur = cv2.blur(img, (5,5))? # 平均法
img_smoth_gaussianblur = cv2.GaussianBlur(img, (5,5), 0) # 高斯模糊
img_smoth_medianblur = cv2.medianBlur(img, 5) # 中值法
titles = ['filter2D', 'blur', 'GaussianBlur', 'medianBlur']
imges = [img_smoth_filter2D, img_smoth_blur, img_smoth_gaussianblur, img_smoth_medianblur]
for i in range(4):
plt.subplot(2,2,i+1), plt.imshow(imges[i])
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.suptitle('smoth images')
plt.show()
# 形態學處理
img2 = cv2.imread('j.png', 0) # 以灰度模式讀取圖像
kernel = np.ones((5,5), np.uint8)
erosion = cv2.erode(img2, kernel, iterations=1) # 腐蝕
dilation = cv2.dilate(img2, kernel, iterations=1) # 膨脹
plt.subplot(1,3,1), plt.imshow(img2, 'gray')
plt.subplot(1,3,2), plt.imshow(erosion, 'gray')
plt.subplot(1,3,3), plt.imshow(dilation, 'gray')
plt.show()