利用Farnback光流算法将视频序列生成光流并输出def preprocessing(): print("开始获取数据...") # clips_directory = gb.glob(os.path.join(datasetTestDir, "*")) # 训练集 clips_directory = gb.glob(os.path.join(datasetTestDir, "Test???")) # 测试集光流生成算法 # 遍历所有数据集中的clip片段 for dir in clips_directory: curClip = dir.split('\\')[-1] print(curClip) img_path = gb.glob(os.path.join(dir, '*.tif')) prvs = cv2.cvtColor(cv2.imread(img_path[0]), cv2.COLOR_BGR2GRAY) hsv = np.zeros_like(cv2.imread(img_path[0])) hsv[..., 1] = 255 for i, curFrame in enumerate(img_path): print("curFrame: ", curFrame) img = cv2.imread(curFrame) next = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) flow = cv2.calcOpticalFlowFarneback(prvs, next, None, 0.5, 3, 15, 3, 5, 1.2, 0) mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1]) hsv[..., 0] = ang * 180 / np.pi / 2 hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX) rgb = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR) # font = cv2.FONT_HERSHEY_SIMPLEX # 使用默认字体 # cv2.putText(img, str(i+1), (0, 20), font, 0.8, (255, 255, 255), 1) # #添加文字,1.2表示字体大小,(0,40)是初始的位置,(255,255,255)表示颜色,2表示粗细 # cv2.putText(rgb, str(i+1), (0, 20), font, 0.8, (255, 255, 255), 1) # #添加文字,1.2表示字体大小,(0,40)是初始的位置,(255,255,255)表示颜色,2表示粗细 cv2.namedWindow("rawImageFrame", 0) cv2.namedWindow("opticalFlowImageFrame", 1) cv2.resizeWindow("rawImageFrame", 360, 240) cv2.resizeWindow("opticalFlowImageFrame", 360, 240) cv2.imshow('rawImageFrame', img) cv2.imshow('opticalFlowImageFrame', rgb) # 将 opticalflow 图像写入相关文档 saveFolder = os.path.join(opticalflowTestDir, curClip) if not os.path.exists(saveFolder): os.makedirs(saveFolder) cv2.imwrite(saveFolder + "\\" + str(i+1) + '.tif', rgb) k = cv2.waitKey(30) & 0xff if k == 27: break elif k == ord('s'): cv2.imwrite('opticalfb.png', img) cv2.imwrite('opticalhsv.png', rgb) prvs = next cv2.destroyAllWindows()
利用Farnback光流算法将视频序列生成光流并输出