opencv 视频压缩 python
时间: 2023-06-19 10:09:39 浏览: 171
使用OpenCV可以对视频进行压缩,下面是一个使用Python的示例代码:
```python
import cv2
# 打开视频文件
video_capture = cv2.VideoCapture('input.avi')
# 视频编解码器
fourcc = cv2.VideoWriter_fourcc(*'XVID')
# 获取视频的宽度和高度
width = int(video_capture.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
# 创建输出视频对象
video_writer = cv2.VideoWriter('output.avi', fourcc, 25.0, (width, height))
# 读取视频帧并压缩
while True:
ret, frame = video_capture.read()
if ret:
# 压缩帧
compressed_frame = cv2.resize(frame, (int(width/2), int(height/2)))
# 写入输出视频
video_writer.write(compressed_frame)
# 显示压缩后的帧
cv2.imshow('Compressed Frame', compressed_frame)
# 按下q键退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# 释放资源
video_capture.release()
video_writer.release()
cv2.destroyAllWindows()
```
在这个示例中,我们使用`cv2.VideoWriter`创建了一个输出视频文件对象,并设置了视频编解码器和帧率。然后,我们读取输入视频的每一帧,对其进行压缩并写入输出视频。
压缩帧的方法在这个示例中是使用`cv2.resize`函数将帧的大小减半。你可以尝试其他的压缩方法来达到不同的压缩效果。
阅读全文
相关推荐














