Pytorch将数据写入视频
- 1. 安装与报错解决
- 2. torch.io程序
- 3. cv2 img文件转视频
- 参考资料
1. 安装与报错解决
- 安装
pip install PyAV
- 报错问题1的解决
报错信息如下:
...tf2_py38\lib\site-packages\torchvision\io\video.py", line 41, in _check_av_availableraise av
ImportError: PyAV is not installed, and is necessary for the video operations in torchvision.
See https://github.com/mikeboers/PyAV#installation for instructions on how to
install PyAV on your system.Process finished with exit code 1
-
报错问题2解决
至于怎么解决PyAV要求的conda的python版本问题
可以参考资料【1】; -
报错问题3解决
这个需要参考我这篇博客,哈哈哈
stream = container.add_stream(video_codec, rate=fps)File "av\\container\\output.pyx", line 67, in av.container.output.OutputContainer.add_streamFile "av\\codec\\codec.pyx", line 185, in av.codec.codec.Codec.__cinit__File "av\\codec\\codec.pyx", line 194, in av.codec.codec.Codec._init
av.codec.codec.UnknownCodecError: libx264
- 最后,直接安装PyAV,安装成功。。。
Collecting PyAVDownloading pyav-12.0.3-cp39-cp39-win_amd64.whl.metadata (2.5 kB)
Downloading pyav-12.0.3-cp39-cp39-win_amd64.whl (19.2 MB)━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 19.2/19.2 MB 223.2 kB/s eta 0:00:00
Installing collected packages: PyAV
Successfully installed PyAV-12.0.3
2. torch.io程序
给出一个写入tensor的demo程序,这个可以用于将tensor数据转换为视频。
import torch
import torchvision.io as io
# tensor生成程序
...
# 将tensor写入视频-设置写入路径
video_path = "path/to/video2.mp4"fps = 1000
# Write the tensor to the video file
io.write_video(video_path, tensor, fps)
3. cv2 img文件转视频
实际上,有时候还是会报错,这里分享个从tensor生成的图片转视频的代码吧:
import cv2
import os# Path to the folder containing the images
folder_path = r'C:\Users\86139\PycharmProjects\pythonProject_at_tsinghua\Event_based_camera_data_extraction\IEBCS-main\examples\00_video_2_events\img3'# Get a list of all image files in the folder
image_files = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]# Sort the image files in ascending order
image_files.sort()# Define the video properties
width, height = 0, 0 # Initialize width and height to 0
fps = 1000 # Frame rate of 1000Hz# Create a VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video_writer = None# Iterate over the image files and write each frame to the video file
for image_file in image_files:# Read the imageimage_path = os.path.join(folder_path, image_file)frame = cv2.imread(image_path)# Get the width and height from the first frameif width == 0 and height == 0:height, width, _ = frame.shape# Create the VideoWriter object on the first iterationif video_writer is None:video_writer = cv2.VideoWriter('./output55.mp4', fourcc, fps, (width, height))# Write the frame to the video filevideo_writer.write(frame)# Release the VideoWriter object
if video_writer is not None:video_writer.release()
参考资料
【1】csdn-conda怎么更新虚拟环境的python版本