I am beginner for the openCV.
I am using below codes to get four video in a file system and show to user. Like this:
V1 | V2
V3 | V4
Video length does not match, If the video comes to end I restart again:
import numpy as np
import cv2
v1 = cv2.VideoCapture('first.avi')
v2 = cv2.VideoCapture('second.avi')
v3 = cv2.VideoCapture('third.avi')
v4 = cv2.VideoCapture('fourth.avi')
v1_length = int(v1.get(cv2.CAP_PROP_FRAME_COUNT))
v2_length = int(v2.get(cv2.CAP_PROP_FRAME_COUNT))
v3_length = int(v3.get(cv2.CAP_PROP_FRAME_COUNT))
v4_length = int(v4.get(cv2.CAP_PROP_FRAME_COUNT))
count1=0
count2 =0
count3= 0
count4 = 0
while True:
ret1, frame1 = v1.read()
ret2, frame2 = v2.read()
ret3, frame3 = v3.read()
ret4, frame4 = v4.read()
# print(ret1,ret2,ret3,ret4)
if count1 == v1_length:
a = v1.set(cv2.CAP_PROP_POS_FRAMES, 0)
print(1,count1)
count1 = 0
if count2 == v2_length:
b = v2.set(cv2.CAP_PROP_POS_FRAMES, 0)
print(2,count2)
count2 = 0
if count3 == v3_length:
c = v3.set(cv2.CAP_PROP_POS_FRAMES, 0)
print(3,count3)
count3 = 0
if count4 == v4_length:
d = v4.set(cv2.CAP_PROP_POS_FRAMES, 0)
print(4,count4)
count4 = 0
if ret1 and ret2 and ret3 and ret4:
s1 = np.hstack((frame1,frame2))
s2 = np.hstack((frame3,frame4))
s3 = np.vstack((s1,s2))
cv2.imshow("Result",s3)
count1 += 1
count2 += 1
count3 += 1
count4 += 1
else:
v1 = cv2.VideoCapture('first.avi')
v2 = cv2.VideoCapture('second.avi')
v3 = cv2.VideoCapture('third.avi')
v4 = cv2.VideoCapture('fourth.avi')
if cv2.waitKey(20) & 0xFF == ord('q'):
break
v1.release()
v2.release()
v3.release()
v4.release()
cv2.destroyAllWindows()
It works but I don't think it's a very good code. How can I write better? How can I increase the number of videos more optimized? For example, how can I simply do it when it is 3x3 grid instead of 2x2 video?