Windows10,NVIDIA 的GPU 1080Ti,自带显卡驱动cuda10
使用的是NVIDIA发布的使用pytorch实现flownet2.0代码,个人比较喜欢pytorch,代码简洁易懂。
github链接: https://github.com/NVIDIA/flownet2-pytorch
之前学习Flownet ( https://github.com/ClementPinard/FlowNetPytorch)时使用KITTI数据集训练效果比较差,于是打算网上下载Fly_chairs数据,但是很多都需要积分和钱,因此我头铁的使用VPN下载了整整一个月(主要是下载很不稳定),为了防止后来者走我这条弯路,这里贴出网盘链接:
https://pan.baidu.com/s/1c3_S0AABXNJVPWQBvkb_ug
密码: bjrf
.zip文件一共30.6G(这里建议开通网盘超级会员,或者找室友借,不然网盘下载速度也很感人),解压之后好像60多G。
这里的环境配置主要是关于gpu版本的pytorch安装,如果电脑配置和我相同的话,配置就比较简单,使用anaconda的conda命令下载即可,其中pytorch和cudnntoolkit的文件较大,建议使用清华源下载到电脑之后再进行线下安装,相关教程网上很多,在此不再赘述。
几点提示:
networks文件夹的编译参考这篇博文有效避坑
其实如果没有遇到相关问题可以直接编译,记得在运行程序的conda环境下编译。
本来想做一个实时的视频分析,但是光流图的出现要经过6s左右,很难做到不卡顿,但是网络实现图片到光流的时间其实只有0.03~0.06s,图像的其他操作加长了处理的速度。
![]() |
![]() |
手部测试视频 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 实现光流视频
![]() |
![]() |
# -*- coding: utf-8 -*-
import numpy as np
import cv2
import warnings
warnings.filterwarnings("ignore")
import torch
import numpy as np
import argparse
import time
from models import FlowNet2 # the path is depended on where you create this module
from utils.flow_utils import flow2img
import matplotlib.pyplot as plt
cap = cv2.VideoCapture('test.mp4')
#获取第一帧
ret, frame1 = cap.read()
prvs = frame1
i = 0 #控制实现的张数
save_path = 'save_path/'
while(1):
ret, frame2 = cap.read()
next = frame2
crop_size = (512, 384)
pim1 = cv2.resize(prvs, crop_size, interpolation = cv2.INTER_CUBIC)
pim2 = cv2.resize(next, crop_size, interpolation = cv2.INTER_CUBIC)
# obtain the necessary args for construct the flownet framework
parser = argparse.ArgumentParser()
parser.add_argument('--fp16', action='store_true', help='Run model in pseudo-fp16 mode (fp16 storage fp32 math).')
parser.add_argument("--rgb_max", type=float, default=255.)
args = parser.parse_args()
# initial a Net
net = FlowNet2(args).cuda()
# load the state_dict
dict = torch.load("FlowNet2_checkpoint.pth.tar")
net.load_state_dict(dict["state_dict"])
images = [pim1, pim2]
images = np.array(images).transpose(3, 0, 1, 2)
im = torch.from_numpy(images.astype(np.float32)).unsqueeze(0).cuda()
start = time.time()
result = net(im).squeeze()
end = time.time()
print(end-start)
data = result.data.cpu().numpy().transpose(1, 2, 0)
img = flow2img(data)
cv2.imwrite(save_path + str(i)+'.png',img)
# plt.imshow(img)
# plt.show()
i = i+1
prvs = next
# -*- coding: UTF-8 -*-
import os
import cv2
import time
def pic2video(path,size):
# path = 'output'#文件路径
filelist = len(os.listdir(path)) #获取该目录下的所有文件名
'''
fps:
帧率:1秒钟有n张图片写进去[控制一张图片停留5秒钟,那就是帧率为1,重复播放这张图片5次]
如果文件夹下有50张 534*300的图片,这里设置1秒钟播放5张,那么这个视频的时长就是10秒
'''
fps = 12
file_path = 'out' + str(int(time.time())) + ".avi" #导出路径
fourcc = cv2.VideoWriter_fourcc('I', '4', '2', '0') #('I','4','2','0' 对应avi格式)
video = cv2.VideoWriter( file_path, fourcc, fps, size )
for i in range(filelist):
i = path + '/' + str(i) +'.png'
img = cv2.imread(i)
video.write(img)
video.release() #释放
pic2video('data_path',(512,384))