系列文章目录
第一章 Python中OpenCV 影像数据处理
文章目录
前言
本文章内容仅为个人笔记,方便日后查阅参考,内容都为基础语法。
一、什么是opencv
就是一个python库,用来处理图像的。
二、图像处理
1.安装库
注意:库不是opencv,而是opencv-python。如果安装失败了,可以从pycharm设置中手动选择下载。
pip install opencv-python
2.加载图片imread
和展示图片imshow
代码如下(示例):
import cv2
img_path = r'../sources/food.png'
#彩色读取imread
image_color = cv2.imread(img_path, cv2.IMREAD_COLOR)
#灰色读取
image_gray = cv2.cvtColor(image_color, cv2.COLOR_BGR2GRAY)
#显示图片imshow
cv2.imshow('color',image_color)
cv2.imshow('gray',image_gray)
#等待用户按键,然后关闭窗口。(没有这个,窗口会一闪而过)
cv2.waitKey(0)#cv2.waitKey(0)是OpenCV库中的一个函数,用于在图像显示的过程中等待用户按键操作。它的参数0表示等待时间为无限大,即程序会一直等待用户按键,直到用户按下任意键为止。
cv2.destroyAllWindows()
3.缩放图片resize
image = cv2.imread(img_path)
#检查图片是否加载
if image is None:
print("Error")
exit()
#获取原始尺寸image.shape:(长,宽,3通道)
height,width = image.shape[:2]
#缩放resize(interpolation=cv2.INTER_AREA差值算法)
new_image = cv2.resize(image_color, (int(height / 2), int(width / 2)), interpolation=cv2.INTER_AREA)
4.旋转图片rotate
rotate_90 = cv2.rotate(image,cv2.ROTATE_90_CLOCKWISE)
'''
顺时针旋转90度ROTATE_90_CLOCKWISE
逆时针旋转90度ROTATE_90_COUNTERCLOCKWISE
'''
5.图片保存imwrite
cv2.imwrite('output.png',image)
三、视频处理
1.视频读取VideoCapture、read
import cv2
#创建对象,参数0表示使用默认摄像头
cap = cv2.VideoCapture(0)#也可以将0替换为视频文件
#一直读取摄像头
while True:
#读取一帧
ret,frame = cap.read()#(True, array([[[120, 118, 123],...[100, 105, 137]]], dtype=uint8))
#显示这帧
if ret:
cv2.imshow('摄像头',frame)
#按q退出
if cv2.waitKey(15) & 0xFF == ord('q'):
break
#释放资源并关闭窗口
cap.release()
cv2.destroyAllWindows
2.视频保存VideoWriter_fourcc、VideoWriter、write
import cv2
#获取对象
cap = cv2.VideoCapture(0)
#判断摄像头是否开启
if not cap.isOpened():
print("Cannot open camera")
exit()
#获取摄像头获取到画面前的长和宽
frameWidth, frameHeight = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
#定义视频编码和输出文件
fourcc = cv2.VideoWriter_fourcc(*'mp4v')#或者使用'XVID' 这里文件打不开,不知道跟这个编码有没有关系
out = cv2.VideoWriter('output.mp4',fourcc, 20.0, (frameWidth, frameHeight))
while True:
ret, frame = cap.read()
frame = cv2.resize(frame, (0,0), fx=0.8, fy=0.8)#设置大小
if not ret:
print("断了")
break
out.write(frame) #将当前帧写入输出视频文件
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#释放资源
cap.release()
out.release()
cv2.destroyAllWindows()
总结
今天就先写到这。