[Python 教程] OpenCV 实战:图像与视频文件处理
OpenCV 实战:图像与视频文件处理
本文详细介绍如何使用 OpenCV 处理图像和视频文件,包括读取、显示、保存等操作。
一、图像文件操作
1.1 读取图像
import cv2
# 读取图像
img = cv2.imread('image.jpg')
# 指定读取方式
gray = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
color = cv2.imread('image.jpg', cv2.IMREAD_COLOR)
# 检查是否读取成功
if img is None:
print("图像加载失败")1.2 显示图像
cv2.imshow('Image Window', img)
cv2.waitKey(0) # 等待按键
cv2.destroyAllWindows()1.3 保存图像
# 保存为 JPG(可设置质量)
cv2.imwrite('output.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, 95])
# 保存为 PNG(无损压缩)
cv2.imwrite('output.png', img, [cv2.IMWRITE_PNG_COMPRESSION, 9])二、视频文件处理
2.1 读取视频
# 打开视频文件
cap = cv2.VideoCapture('video.mp4')
# 或者打开摄像头
# cap = cv2.VideoCapture(0)
# 检查是否成功
if not cap.isOpened():
print("无法打开视频")
# 获取视频属性
fps = cap.get(cv2.CAP_PROP_FPS)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
print(f"FPS: {fps}, 分辨率:{width}x{height}, 总帧数:{total_frames}")2.2 逐帧处理
while True:
ret, frame = cap.read()
if not ret: # 视频结束
break
# 处理帧(例如转为灰度)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 显示
cv2.imshow('Video', gray)
# 按 q 退出
if cv2.waitKey(25) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()2.3 保存视频
cap = cv2.VideoCapture('input.mp4')
# 获取视频信息
fps = cap.get(cv2.CAP_PROP_FPS)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# 创建 VideoWriter
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('output.mp4', fourcc, fps, (width, height))
while True:
ret, frame = cap.read()
if not ret:
break
# 处理帧
processed = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
processed = cv2.cvtColor(processed, cv2.COLOR_GRAY2BGR)
# 写入
out.write(processed)
cap.release()
out.release()
cv2.destroyAllWindows()三、摄像头实时捕获
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
# 添加文字
cv2.putText(frame, 'Press Q to quit', (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.imshow('Camera', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()四、实用技巧
4.1 批量处理图像
import os
image_folder = 'images'
for filename in os.listdir(image_folder):
if filename.endswith('.jpg'):
img = cv2.imread(os.path.join(image_folder, filename))
# 处理图像
processed = cv2.resize(img, (224, 224))
cv2.imwrite(f'output_{filename}', processed)4.2 视频帧提取
cap = cv2.VideoCapture('video.mp4')
frame_count = 0
while True:
ret, frame = cap.read()
if not ret:
break
# 每 30 帧保存一次
if frame_count % 30 == 0:
cv2.imwrite(f'frame_{frame_count}.jpg', frame)
frame_count += 1
cap.release()五、总结
本文介绍了 OpenCV 中图像和视频文件的基本操作方法,包括读取、显示、保存,以及视频流处理和摄像头捕获。这些是计算机视觉项目的基础技能。
