一、安装环境
我是在anaconda3下面建立的虚拟环境,pip下载opencv
pip install opencv-python
二、CV2
导入函数库
import cv2
import numpy as np
import matplotlib.pyplot as plt
读取图片,并显示
img_file = 'luo.jpg'
img_rgb = cv2.imread(img_file) # 已彩色模式读取图像文件
rows, cols, ch = img_rgb.shape # 获取图像形状
print(rows, cols, ch) #打印图片尺寸
cv2.imshow("RGBIMG", img_rgb)
cv2.waitKey(0) # 只显示第一帧
cv2.destroyAllWindows() # 销毁所有的窗口
读取视频,并显示
video = cv.VideoCapture('test.mp4')
#检查是否正确打开isOpened()
#循环读取每一帧
while video.isOpened():
ret, frame = video.read()
if frame is None:
break
if ret == True:
cv.imshow("result", frame)
#100 : 表示一帧等待一百毫秒在进入下一帧, 0xFF : 表示键入键 27 = esc
if cv.waitKey(100) & 0xFF == 27 :
break
#释放视频
video.release()
cv.destroyAllWindows()
图像处理
import cv2
import numpy as np
import matplotlib.pyplot as plt
img_file = 'luo.jpg'
img_rgb = cv2.imread(img_file) # 已彩色模式读取图像文件
################################图像显示###############################
rows, cols, ch = img_rgb.shape # 获取图像形状
print(rows, cols, ch)
cv2.imshow("RGBIMG", img_rgb)
##############################图像缩放################################
#缩小图像
size=(int(rows*0.5),int(cols*0.3))
img_scale_1 = cv2.resize(img_rgb, size, interpolation=cv2.INTER_CUBIC)
#放大图片
img_scale_2 = cv2.resize(img_rgb, None, fx=1.6,fy=1.2, interpolation=cv2.INTER_CUBIC)
cv2.imshow("RGBRESIZE_1", img_scale_1)
cv2.imshow("RGBRESIZE_2", img_scale_2)
###########################图像平移###################################
M = np.float32([[1,0,100],[0,1,50]]) # x=>100, y=>50
img_transform = cv2.warpAffine(img_rgb, M, (cols,rows),borderValue=(255,255,255)) # 平移图像,borderValue边缘填充颜色
print(img_transform.shape)
cv2.imshow('transform img', img_transform)
############################图像旋转#############################
M = cv2.getRotationMatrix2D((cols/2, rows/2), 45, 0.6)
img_rotation = cv2.warpAffine(img_rgb, M, (cols, rows))
cv2.imshow('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_rgb, M, (x,y))
# cv2.imshow('perspective img', img_perspective)
##################### 转化为灰度图片########################
gray_img = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY) # 图像转灰色
cv2.imshow('gray img', gray_img)
###########################边缘检测######################
edge_img = cv2.Canny(img_rgb, 250,250) #250和250是上下阈值。如果改变上下阈值,就会出现不同的结果
cv2.imshow('edge img', edge_img)
###########################二值化处理####################
ret, th1 = cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY) # 127为阀值,255为(超过或小于阀值)赋予的值,THRESH_BINARY类型
th2 = cv2.adaptiveThreshold(gray_img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11,2) #均值阀值,11=>图像分块数, 2=>计算阀值的常数项
th3 = cv2.adaptiveThreshold(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_rgb, -1, kernel) # 2D 卷积法
img_smoth_blur = cv2.blur(img_rgb, (5,5)) # 平均法
img_smoth_gaussianblur = cv2.GaussianBlur(img_rgb, (5,5), 0) # 高斯模糊
img_smoth_medianblur = cv2.medianBlur(img_rgb, 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()
cv2.waitKey(0) # 只显示第一帧
cv2.destroyAllWindows() # 销毁所有的窗口