Created
March 6, 2018 07:12
-
-
Save ryosism/5c58ce4d310ab82a7703d36fb2735a44 to your computer and use it in GitHub Desktop.
オプティカルフロー形式のファイル(.flo)を.pngに変換するスクリプト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Python 2/3 compatibility | |
from __future__ import print_function | |
# modded by ryosism | |
# sys.argv[1] : input .flo file | |
# sys.argv[2] : output .png file | |
import cv2 as cv | |
import numpy as np | |
import sys | |
import os | |
TAG_FLOAT = 202021.25 | |
def read(file): | |
assert type(file) is str, "file is not str %r" % str(file) | |
assert os.path.isfile(file) is True, "file does not exist %r" % str(file) | |
assert file[-4:] == '.flo', "file ending is not .flo %r" % file[-4:] | |
f = open(file,'rb') | |
flo_number = np.fromfile(f, np.float32, count=1)[0] | |
assert flo_number == TAG_FLOAT, 'Flow number %r incorrect. Invalid .flo file' % flo_number | |
w = np.fromfile(f, np.int32, count=1) | |
h = np.fromfile(f, np.int32, count=1) | |
#if error try: data = np.fromfile(f, np.float32, count=2*w[0]*h[0]) | |
data = np.fromfile(f, np.float32, count=2*w*h) | |
# Reshape data into 3D array (columns, rows, bands) | |
flow = np.resize(data, (int(h), int(w), 2)) | |
f.close() | |
return flow | |
def draw_hsv(flow): | |
h, w = flow.shape[:2] | |
fx, fy = flow[:,:,0], flow[:,:,1] | |
ang = np.arctan2(fy, fx) + np.pi | |
v = np.sqrt(fx*fx+fy*fy) | |
hsv = np.zeros((h, w, 3), np.uint8) | |
hsv[...,0] = ang*(180/np.pi/2) | |
hsv[...,1] = 255 | |
hsv[...,2] = np.minimum(v*4, 255) | |
bgr = cv.cvtColor(hsv, cv.COLOR_HSV2BGR) | |
return bgr | |
def write(flow): | |
cv.imwrite(sys.argv[2], draw_hsv(flow)) | |
if __name__ == '__main__': | |
flo = sys.argv[1] | |
opticalFlow = read(flo) | |
write(opticalFlow) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment