系列文章目录
第一章 Python中OpenCV 影像数据处理
文章目录
前言
本文章内容仅为个人笔记,方便日后查阅参考,内容都为基础语法。
一、什么是opencv
就是一个python库,用来处理图像的。
二、图像处理
1.安装库
注意:库不是opencv,而是opencv-python。如果安装失败了,可以从pycharm设置中手动选择下载。
pip install opencv-python
2.加载图片imread
、改变颜色cvtColor
、展示图片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()
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()
四、视频处理综合案例
获取帧数、大小cap.get(cv2.CAP_PROP_***)
创建视频写入对象
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(output_video, fourcc, fps, (new_width, new_height), isColor=False)
调整帧大小resize
转换为灰度图像cvtColor
垂直翻转画面flip(frame,1)
题目:用OpenCV打开一段视频,将每一帧画面压缩成540p,对画面进行垂直翻转,转为黑白,然后添加高斯噪声,把处理好的每一画面保存成一个mp4文件
import cv2
import numpy as np
# 添加高斯噪声函数
def add_gaussian_noise(img):
row, col = img.shape # 获取画面尺寸信息
mean = 0 # 平均值为0
sigma = 15 # 西格玛为15
gauss = np.random.normal(mean, sigma, (row, col)) # 高斯纯噪声
noisy = img + gauss # 高斯噪声和图片本身叠加
noisy_img = np.clip(noisy, 0, 255) # 确保噪声值在0到255之间
return noisy_img.astype(np.uint8) # 整数形式返回
# 定义输入输出视频路径
input_video = 'demo.mp4'
output_video = 'resource.mp4'
# 打开输入视频
cap = cv2.VideoCapture(input_video)
# 获取视频的帧率和帧大小
fps = cap.get(cv2.CAP_PROP_FPS)
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# 计算新的帧大小(540p)
new_height = 540
new_width = int(frame_width * new_height / frame_height)
# 创建视频写入对象
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(output_video, fourcc, fps, (new_width, new_height), isColor=False)
while True:
ret, frame = cap.read()
if not ret:
break
# 调整帧大小
frame = cv2.resize(frame, (new_width, new_height))
# 转换为灰度图像
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 垂直翻转画面
frame = cv2.flip(frame, 1)
# 添加高斯噪声
frame = add_gaussian_noise(frame)
# 写入输出视频
out.write(frame)
cv2.imshow('frame', frame)
# 释放资源
cap.release()
out.release()
cv2.destroyAllWindows()
总结
这些都是python处理图像和视频的代码,以后写项目中总能遇到。回头查阅即可。