JavaScript
x
27
27
1
import cv2
2
cap = cv2.VideoCapture(input_path)
3
4
count = 0
5
n=0
6
while True:
7
ret, frame = cap.read()
8
9
if ret:
10
# You can do processing on this frame variabqle
11
roi = frame[343:489, 572:759]
12
# frame = cv2.resize(roi, None, fx=0.9, fy=0.9)
13
14
cv2.imshow("roi", roi)
15
16
17
18
cv2.imshow("image", frame)
19
if cv2.waitKey(1) & 0xFF == ord('q'):
20
break
21
else:
22
break
23
24
25
26
cv2.destroyAllWindows()
27
I want the first frame of video to compare with other frames of video and calculate ssim (similarity) based on the first frame. How to do this search a lot but not getting the desired result.
Advertisement
Answer
@Ceopee is right and there is no error in that tutorial.
The idea is simple:
JavaScript
1
6
1
if count is 0
2
get the first frame
3
else
4
calculate ssim of frame1 and the next-frame
5
display
6
Code:
JavaScript
1
66
66
1
import cv2
2
import numpy as np
3
4
5
def ssim(i1, i2):
6
c1 = 6.5025
7
c2 = 58.5225
8
# INITS
9
I1 = np.float32(i1) # cannot calculate on one byte large values
10
I2 = np.float32(i2)
11
I2_2 = I2 * I2 # I2^2
12
I1_2 = I1 * I1 # I1^2
13
I1_I2 = I1 * I2 # I1 * I2
14
# END INITS
15
# PRELIMINARY COMPUTING
16
mu1 = cv2.GaussianBlur(I1, (11, 11), 1.5)
17
mu2 = cv2.GaussianBlur(I2, (11, 11), 1.5)
18
mu1_2 = mu1 * mu1
19
mu2_2 = mu2 * mu2
20
mu1_mu2 = mu1 * mu2
21
sigma1_2 = cv2.GaussianBlur(I1_2, (11, 11), 1.5)
22
sigma1_2 -= mu1_2
23
sigma2_2 = cv2.GaussianBlur(I2_2, (11, 11), 1.5)
24
sigma2_2 -= mu2_2
25
sigma12 = cv2.GaussianBlur(I1_I2, (11, 11), 1.5)
26
sigma12 -= mu1_mu2
27
t1 = 2 * mu1_mu2 + c1
28
t2 = 2 * sigma12 + c2
29
t3 = t1 * t2 # t3 = ((2*mu1_mu2 + C1).*(2*sigma12 + C2))
30
t1 = mu1_2 + mu2_2 + c1
31
t2 = sigma1_2 + sigma2_2 + c2
32
t1 = t1 * t2 # t1 =((mu1_2 + mu2_2 + C1).*(sigma1_2 + sigma2_2 + C2))
33
ssim_map = cv2.divide(t3, t1) # ssim_map = t3./t1;
34
mssim = cv2.mean(ssim_map) # mssim = average of ssim map
35
return mssim
36
37
38
cap = cv2.VideoCapture("b/ex.mp4")
39
40
count = 0
41
frm1 = -1
42
43
cv2.namedWindow("frame-1")
44
cv2.moveWindow("frame-1", 800, 0)
45
46
while cap.isOpened():
47
ret, frm = cap.read()
48
49
if ret:
50
if count == 0:
51
frm1 = frm
52
else:
53
mssimv = ssim(frm1, frm)
54
print("nMSSISM: R {}% G {}% B {}%".format(round(mssimv[2] * 100, 2), round(mssimv[1] * 100, 2),
55
round(mssimv[0] * 100, 2)), end=" ")
56
cv2.imshow("frame-1", frm1)
57
cv2.imshow("frame-{}".format(count), frm)
58
if cv2.waitKey(1) & 0xFF == ord('q'):
59
break
60
count += 1
61
else:
62
break
63
64
cap.release()
65
cv2.destroyAllWindows()
66