Sunday, 6 March 2022

How to convert video to gif using python opencv

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import cv2
from sklearn.metrics import mean_squared_error
from math import sqrt
import numpy as np
import traceback as tb
import images_to_gif as ig
from PIL import Image

cap = cv2.VideoCapture('..\\test\\videoplayback.mp4')
# Check if camera opened successfully
if (cap.isOpened()== False): 
  print("Error opening video  file")
farmes_list = list()
while(cap.isOpened()):
	ret, frame = cap.read()
	ret, frame = cap.read()
	if ret == True:
		# Display the resulting frame
		cv2.imshow('Frame', frame)
		farmes_list.append(frame)
	else:
		break
	# Press Q on keyboard to  exit
	if cv2.waitKey(25) & 0xFF == ord('q'):
		break

print(f'length of the frame list is= {len(farmes_list)}')
i = 0
new_frame = list()
for img in farmes_list:
	try:
		frame = img
		# Open image in bwDir - The searched image
		searchedImageBw = np.array(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))
		# Open image to be compared
		inx = i
		if inx != len(farmes_list):
			cmpImage = np.array(cv2.cvtColor(farmes_list[inx+1], cv2.COLOR_BGR2GRAY))
			rms = sqrt(mean_squared_error(searchedImageBw, cmpImage))
			print(f'rms= {rms}')
			if rms>3:
				#farmes_list.remove(frame)
				new_frame.append(frame)


	except Exception as e:
		print(e)
		tb.print_exc()
		pass
	i = i+1
   

print(f'length of the frame list is= {len(new_frame)}')

pil_frame = [ Image.fromarray(img) for img in new_frame]
bytesio_object = ig.frame_gif(pil_frame)
ig.save(bytesio_object, path = "videotogif.gif")
cap.release()
cv2.destroyAllWindows()