Sie sind auf Seite 1von 14

Vaman Teodora TAID 2022

Referat Laborator 4 SSCV

Aplicatia 1
➔ Adnotarile sunt prezente in fisierul GT_Friends
➔ Majoritatea tranzitiilor sunt de tip abrupt, dar exista si de tip fade (personal, am
observant 33)
➔ S-a observant ca majoritatea tranzitiilor fade dureaza un singur cadru ( cadruA ->
cadruA+B -> cadrul B ) cu exceptia unor tranzitii ce dureaza maim ult (maximul a fost de
30 de cadre intermediare) care apar in momentul in care subiectul scenelor se schimba
foarte mult

Aplicatia 2
Metoda 1
Th value DCut DGradual MDCut MD FA
0.5 45 67 0 14 39
0.6 45 107 0 11 3
0.7 45 226 0 4 147

Th = 0.7 :
Precision: 0.6483253588516746
Recall: 0.9854545454545455
F1 score: 0.7821067821067821

Th = 0.6:
Precision: 0.7958115183246073
Recall: 0.7307692307692307
F1 score: 0.7619047619047619
Vaman Teodora TAID 2022

Th = 0.5:
Precision: 0.7958115183246073
Recall: 0.9325153374233128
F1 score: 0.8587570621468925

Threshold-ul cu rezultatul cel mai bun este 0.6


Metoda 2
Th value DCut DGradual MDCut MD FA
0.5 0 0 45 34 0

Cod:

from skimage.metrics import structural_similarity


import cv2
import numpy as np
#################################################################################
####################################
#################################################################################
####################################

#################################################################################
####################################
#################################################################################
####################################

#################################################################################
####################################
#################################################################################
####################################

#################################################################################
####################################
#################################################################################
####################################
Vaman Teodora TAID 2022

#################################################################################
####################################
#################################################################################
####################################
def saveVideoFrames(videoFilePath):

pathFolderWhereToSaveFrames = ".//VideoFrames//"

#TO DO for Application 1.1. - Save each frame of the video stream by marking
on the saved image the frame number.
#The frames will be saved as "xxxx.jpg", where xxxx is the number of the
video frame padded with leading zero

# Opens the Video file


cap= cv2.VideoCapture('E:\Lucru\ANUL II MASTER\SCCV\Laborator\LAborator
4\VideoTemporalSegmentation_ForStudents\Friends.mp4')
i=0
while(cap.isOpened()):
ret, frame = cap.read()
if ret == False:
break
cv2.imwrite(".//VideoFrames//"+str(i)+'.jpg',frame)
i+=1

# cap.release()
# cv2.destroyAllWindows()

return
#################################################################################
####################################
#################################################################################
####################################

#################################################################################
####################################
#################################################################################
####################################
def shotBoundaryDetection(frames, videoFilePath, method = 1):

#TO DO for Application 2 - This function will automatically identify the shot
boundaries for the input video.
Vaman Teodora TAID 2022

#The function returns a list of elements containing all the locations where a
shot boundary has been identified.

listOfTransitions = []

threshold = 0.5 #This threshold should be modified accordingly to the


exercices
if method == 1:
threshold = 0.7
elif method == 2:
threshold = 0.6

for index in range(len(frames) - 1):


tmp_ssim = dif2FramesSSIM(frames[index], frames[index + 1])

if method == 1:
tmp_ssim = dif2FramesSSIM(frames[index], frames[index + 1])
elif method == 2:
tmp_ssim = dif2FramesHist(frames[index], frames[index + 1])

if tmp_ssim < threshold :


listOfTransitions.append(index + 1)

return listOfTransitions
#################################################################################
####################################
#################################################################################
####################################

#################################################################################
####################################
#################################################################################
####################################
def dif2FramesSSIM(frameAnt, frameCrt):

#TO DO for Application 2 - Method 1 - This function compute the difference


between the two video frames
#together with the associated structural similarity index measure (SSIM)

similarityScore = 0
Vaman Teodora TAID 2022

# TO DO - Convert frames to grayscale


frameAnt_gray = cv2.cvtColor(frameAnt,cv2.COLOR_BGR2GRAY)
frameCrt_gray = cv2.cvtColor(frameCrt,cv2.COLOR_BGR2GRAY)

# TO DO - Compute SSIM between two images using the structural_similarity


function from scikit-image library
(similarityScore, diff) = structural_similarity(frameAnt_gray, frameCrt_gray,
full=True)
# print("Image similarity", similarityScore)

return similarityScore
#################################################################################
####################################
#################################################################################
####################################

#################################################################################
####################################
#################################################################################
####################################
def dif2FramesHist(frameAnt, frameCrt, metric = 1):

# TO DO for Application 2 - Method 2 - This function compute the difference


between the two video frames
# using a distance metric between color histograms
simHist = 0

# Convert frames from bgr to rgb


frameAnt = cv2.cvtColor(frameAnt, cv2.COLOR_BGR2RGB)
frameCrt = cv2.cvtColor(frameCrt, cv2.COLOR_BGR2RGB)

# Compute RGB color histogram; We’ll be extracting a 3D RGB color histogram


with 8 bins per channel
# channels = [0, 1, 2] because we need to process both R, G and B planes.
# bins = [8,8,8] for each plane.
# range = [0, 255, 0, 255, 0, 255] the value for the R, G and B lie between 0
and 255.

histogramAnt = histogramCrt= np.zeros((3,8))

for i in range(3):
Vaman Teodora TAID 2022

histogramAnt[i,:] = np.histogram(frameAnt[:,:,i], bins = 8, range =


(0,255) )[0]
histogramCrt[i,:] = np.histogram(frameCrt[:,:,i], bins = 8, range =
(0,255) )[0]

# TO DO - The histograms are further normalized and flatten.

for i in range(3):
histogramAnt[i, :] = histogramAnt[i, :] / np.sum(histogramAnt[i, :])
histogramCrt[i, :] = histogramCrt[i, :] / np.sum(histogramCrt[i, :])

histogramAnt = histogramAnt.flatten().astype(np.float32)
histogramCrt = histogramCrt.flatten().astype(np.float32)

# Compare the image histograms using different metrics: cv2.HISTCMP_CORREL,


cv2.HISTCMP_CHISQR, cv2.HISTCMP_INTERSECT

hist_metric = cv2.HISTCMP_CORREL
if metric == 1:
hist_metric = cv2.HISTCMP_CORREL
elif metric == 2:
hist_metric = cv2.HISTCMP_CHISQR
elif metric == 2:
hist_metric = cv2.HISTCMP_INTERSECT

similarity_hist = cv2.compareHist(histogramAnt, histogramCrt, hist_metric)

return similarity_hist
#################################################################################
####################################
#################################################################################
####################################

#################################################################################
####################################
#################################################################################
####################################
def dif2FramesInterestPoints(frameAnt, frameCrt):

# TO DO for Application 2 - Method 3 - This function compute the similarity


between two video frames
# as the number of matched interest points
Vaman Teodora TAID 2022

# TO DO - Convert frames to grayscale

#TO DO - Initiate SIFT detector

#TO DO - Find the keypoints and describe them with SIFT

#TO DO - Match the points using FlannBasedMatcher and retain as good the ones
verifying the Lowe's ratio test
goodMatches = []
loweRation = 0.75

return len(goodMatches)
#################################################################################
####################################
#################################################################################
####################################

#################################################################################
####################################
#################################################################################
####################################
def verifyAgainsGT(groundthruthFilePath, listOfTransitions):

#TO DO for Application 2.1.1 - this function compare the list of detected
transitions with the ground truth.

#TO DO - Open the the file with the Ground Truth and read it line by line
#You may also want to remove whitespace characters like `\n` at the end of
each line
Vaman Teodora TAID 2022

#The content of the listOfTransitions_GT variable should be:


#[200, 325, [447, 449], [586, 588], 681, ...]

with open(groundthruthFilePath) as f:
lines = f.read().splitlines()

GT_frames = []
for item in lines:
item = item.split(' ')
if (len(item) == 1):
GT_frames.append([item[0]])
else:
GT_frames.append([item[0], item[1]])

# print(GT_frames)

#Lists of detected/not detected transitions and false alarm


list_D_Cut = [] #The list with the detected abrupt transitions
list_D_Gradual = [] #The list with the detected gradual transitions
list_MD_Cut = [] #The list with the miss detected abrupt transitions
list_MD_Gradual = [] #The list with the miss detected gradual transitions
list_FA = [] #The list with the false alarms

#TO DO - perform the validation of the listOfTransitions against the


listOfTransitions_GT

# detected => se afla in listOfTransitions si in GT_frames


# missed => nu se afla in listOfTransitions dar se afla in in GT_frames
# false alarm => se afla in listOfTransitions dar nu se afla in GT_frames

for transition in listOfTransitions:

false_alarm = 1

for gt_frame in GT_frames:


if len(gt_frame) > 1 and transition >= int(gt_frame[0]) and
transition <= int(gt_frame[1]):
false_alarm = 0

# print("Gradual -- transition: {} - GT: {} ------


{}".format(transition, gt_frame, len(gt_frame) ))
elif transition == int(gt_frame[0]):
false_alarm = 0
list_D_Cut.append(transition)
Vaman Teodora TAID 2022

# print("Abrupt -- transition: {} - GT:


{}".format(transition, gt_frame ))
list_D_Gradual.append(transition)
if false_alarm == 1:
list_FA.append(transition)

for gt_frame in GT_frames:

if len(gt_frame) == 1:
if int(gt_frame[0]) not in listOfTransitions:
list_MD_Cut.append(gt_frame)
# print("Abrupt -- transition: {} - GT: {}".format(transition,
gt_frame ))

elif len(gt_frame) > 1:


isNotFound = 1
for transition in listOfTransitions:
if transition >= int(gt_frame[0]) and transition <=
int(gt_frame[1]):
isNotFound = 0
break
if isNotFound == 1:
list_MD_Gradual.append(gt_frame)
# print("Gradual -- transition: {} - GT: {} ------
{}".format(transition, gt_frame, len(gt_frame) ))

#Print the performance results


print("The number of the detected abrupt transitions:
{}".format(len(list_D_Cut)))
print("The number of the detected gradual transitions:
{}".format(len(list_D_Gradual)))
print("The number of the miss detected abrupt transitions
{}".format(len(list_MD_Cut)))
print("The number of the miss detected gradual transitions
{}".format(len(list_MD_Gradual)))
print("The number of false alarms {}".format(len(list_FA)))

#TO DO - Compute the global system performances using Precision, Recall and
F1 score
precision = 0
recall = 0
f1score = 0
Vaman Teodora TAID 2022

precision = (len(list_D_Cut) + len(list_D_Gradual)) / (len(list_D_Cut) +


len(list_D_Gradual) + len(list_FA) + 1e-10)
recall = (len(list_D_Cut) + len(list_D_Gradual)) / (len(list_D_Cut) +
len(list_D_Gradual) + len(list_MD_Cut) + len(list_MD_Gradual) + 1e-10)
f1score = 2 * precision * recall / (precision + recall + 1e-10)

#Print the global system performance


print("Precision: {}".format(precision))
print("Recall: {}".format(recall))
print("F1 score: {}".format(f1score))

return
#################################################################################
####################################
#################################################################################
####################################

#################################################################################
####################################
#################################################################################
####################################
def keyFrameSelection (videoFilePath, listOfTransitions):

# TO DO for Application 3.1 - This function should extract one KeyFrame per
shot
# and save the images in the KeyFrames Folder

pathFolderWhereToSaveKeyFrames = ".//KeyFrames//"
listKeyFrames = []

return listKeyFrames
#################################################################################
####################################
#################################################################################
####################################

#################################################################################
####################################
#################################################################################
####################################
def main():
Vaman Teodora TAID 2022

videoFilePath = ".//Friends.mp4"
groundthruthFilePath = ".//GT_Friends.txt"

cap= cv2.VideoCapture('E:\Lucru\ANUL II MASTER\SCCV\Laborator\LAborator


4\VideoTemporalSegmentation_ForStudents\Friends.mp4')
i=0
frames = []
while(cap.isOpened()):
ret, frame = cap.read()
if ret == False:
break
frames.append(frame)
# cv2.imwrite(".//VideoFrames//"+str(i)+'.jpg',frame)

#Application 1.1
# saveVideoFrames(videoFilePath)

#Application 2
listOfTransitions = shotBoundaryDetection(frames, videoFilePath, 2)

print(len(listOfTransitions))

# print(listOfTransitions)

verifyAgainsGT('./GT_Friends.txt', listOfTransitions)
# #Application 2.1.1
# verifyAgainsGT(groundthruthFilePath, listOfTransitions)

# #Application 3
# keyFrameSelection(videoFilePath, listOfTransitions)

return
#################################################################################
####################################
#################################################################################
####################################

#################################################################################
####################################
Vaman Teodora TAID 2022

#################################################################################
####################################
if __name__ == '__main__':
main()
#################################################################################
####################################
#################################################################################
####################################

GroundTruth:
200
325
447 449
586 588
681
996 968
1075 1077
1145
1338 1340
1458 1460
1518 1520
1575
1646 1672
1710 1740
2146
2354
2444 2446
2594 2596
2788
2977
3023
3096 3098
3332
3503
3570 3572
3655 3657
3741 3800
3818
3893
3982 3984
Vaman Teodora TAID 2022

4273
4406
4528
4575
4643
4935
5009
5295
5437 5439
5549
5656 5658
5700 5726
5785
5875
5930 5932
5982 5985
6240
6306
6415
6462 6464
6504 6506
6691 6693
6794
6894
6964
7046 7048
7136 7140
7169 7201
7420 7422
7560
7650
7824
7950
8025 8027
8124
8201
8263
8330
8501 8503
8691
8769
8855 8858
8921
9000 9003
Vaman Teodora TAID 2022

9069 9071
9169
9337
9418 9421
9487

Das könnte Ihnen auch gefallen