#coding = utf-8
import cv2
import numpy as np
from pylab import *
import matplotlib.pyplot as plt
import pdb
frame1 =cv2.imread(r"tes1t.png")
# cap = cv2.VideoCapture(‘GOPR1745.avi‘)
# ret, frame1 = cap.read()
prvs = cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY)
# ret, frame2 = cap.read()
frame2 =cv2.imread(r"tes2t.png")
next = cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY)
flow = cv2.calcOpticalFlowFarneback(prvs,next, 0.5, 3, 15, 3, 10, 1.2, 0)
size = flow.shape
print size
delta_x = flow[:,:,0]
delta_y = flow[:,:,1]
u = delta_x
v = delta_y
print ‘u‘,u ,‘v‘,v
contourf(u)
colorbar()
show()
contourf(v)
colorbar()
show()
plt.figure()
Q = plt.quiver(u, v)
qk = plt.quiverkey(Q, 0.5, 0.98, 2, r‘$2 \frac{m}{s}$‘, labelpos=‘W‘,
fontproperties={‘weight‘: ‘bold‘})
l, r, b, t = plt.axis()
dx, dy = r - l, t - b
plt.axis([l - 0.05*dx, r + 0.05*dx, b - 0.05*dy, t + 0.05*dy])
plt.title(‘flow picture‘)
xx = np.arange(size[1])
yy = np.arange(size[0])
g_xx,g_yy = np.meshgrid(xx,yy)
print ‘xx.shape‘,xx.shape,‘yy.shape‘,yy.shape
print ‘g_xx.shape‘,g_xx.shape,‘g_yy.shape‘,g_yy.shape
new_image = frame1.copy()
for i in range(size[0]):
for j in range(size[1]):
try:
new_image[i,j,:]=frame1[i+int(round(delta_x[i,j])),j+int(round(delta_y[i,j])),:]
except:
new_image[i,j,:] = [0,0,0]
# # pdb.set_trace()
# ng_xx = g_xx + delta_x
# ng_yy = g_yy + delta_y
# ng_xx[ng_xx <0] = 0
# ng_xx[ng_xx>size[0]-1]=size[0]-1
# ng_yy[ng_yy <0] = 0
# ng_yy[ng_yy>size[1]-1]=size[1]-1
# ng_xx = np.asarray(ng_xx,dtype="int64")
# ng_yy = np.asarray(ng_yy,dtype="int64")
# new_image = frame1.copy()
# new_image[g_yy,g_xx,:] = frame1[ng_yy,ng_xx,:]
fig, axes = plt.subplots(nrows=2, ncols=2)
ax0, ax1, ax2, ax3 = axes.flat
ax0.imshow(frame1)
ax1.imshow(frame2)
ax2.imshow(new_image)
ax3.imshow(new_image-frame1)
show()
# plt.figure()
# Q = plt.quiver(u[::20,::20],v[::-20,::-20])
# qk = plt.quiverkey(Q, 0.5, 0.92, 2, r‘$2 \frac{m}{s}$‘, labelpos=‘W‘,
# fontproperties={‘weight‘: ‘bold‘})
# imshow(v)
# colorbar()
#