opencv-python DIS光流

# -牧野- 2021-05-29
import cv2
from flowlib import flow_to_image
import numpy as np

def warp_flow(img, flow):
    h, w = flow.shape[:2]
    flow = -flow
    flow[:,:,0] += np.arange(w)
    flow[:,:,1] += np.arange(h)[:,np.newaxis]
    res = cv2.remap(img, flow, None, cv2.INTER_LINEAR)
    return res

img0_path = 'im1.png'
img1_path = 'im3.png'

img0 = cv2.imread(img0_path)
img1 = cv2.imread(img1_path)

img0_gray = cv2.cvtColor(img0, cv2.COLOR_BGR2GRAY)
img1_gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)

dis = cv2.DISOpticalFlow_create(2)  #PRESET_ULTRAFAST, PRESET_FAST and PRESET_MEDIUM
flow0 = dis.calc(img0_gray, img1_gray, None, )
flow1 = dis.calc(img1_gray, img0_gray, None, )

img1_warp = warp_flow(img0, flow0)
img0_warp = warp_flow(img1, flow1)

flow0_img = flow_to_image(flow0)
flow1_img = flow_to_image(flow1)

cv2.imwrite('flow0.jpg', flow0_img)
cv2.imwrite('flow1.jpg', flow1_img)
cv2.imwrite('im3_warp.jpg', img1_warp)
cv2.imwrite('im1_warp.jpg', img0_warp)

引用的flowlib.py文件见https://github.com/liruoteng/OpticalFlowToolkit/blob/master/lib/flowlib.py

输入图像:

opencv-python DIS光流_第1张图片opencv-python DIS光流_第2张图片

 

0:PRESET_ULTRAFAST 1:PRESET_FAST   2:PRESET_MEDIUM对应结果:

opencv-python DIS光流_第3张图片opencv-python DIS光流_第4张图片opencv-python DIS光流_第5张图片

warp结果:

opencv-python DIS光流_第6张图片opencv-python DIS光流_第7张图片

你可能感兴趣的:(OpenCV-Python)