环境: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()