Skip to content
Snippets Groups Projects
Commit f227dbff authored by Leonardo de Lima Gaspar's avatar Leonardo de Lima Gaspar
Browse files

Cleaned up some code and csv reading logic. Should work as standalone.

parent ce19626d
No related branches found
No related tags found
No related merge requests found
......@@ -22,9 +22,6 @@ bool detectChange(Mat firstFrame, Mat secFrame);
double percentChangeThreshold = 0.00048828125; // 2^-11
int main(int argc, char** argv) {
if (argc != 2) {
cerr << "Have to pass 1 and only 1 argument.";
......@@ -128,7 +125,7 @@ int main(int argc, char** argv) {
runEnd_s = runStart_s + timePerSimFrame_s*runCounter;
i += runCounter;
if (runCounter>0) {
csv << (int)runStart_s << "," << (int)runEnd_s << endl;
csv << (int)runStart_s << "," << (int)runEnd_s << ",";
}
}
......
......@@ -2,7 +2,6 @@ import os
import sys
import ctypes
import VideoTrimmer
import Jaccard
def is_admin():
try:
......@@ -17,7 +16,6 @@ def main(inputVideo):
# Relative path to input folder from the current working directory (often the root of the repo).
repoRootToBinary = "build\\Release"
pathToBinary = os.path.join(curDir, repoRootToBinary)
print("halo")
os.chdir(pathToBinary)
# Creates input/output folders for videofiles.
......@@ -34,6 +32,6 @@ def main(inputVideo):
prefix, ext = os.path.splitext(inputVideo)
print("\nVideo processed and outputted to {csv}.".format(csv=prefix+".csv"))
print("Starting trimming now...")
VideoTrimmer.readForCSV(pathToBinary)
VideoTrimmer.readForCSV(inputVideo)
main("test.mp4")
\ No newline at end of file
main("Myggbukta-[2021-07-09_13-48-44]-105.mp4")
\ No newline at end of file
from moviepy.editor import VideoFileClip
from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip
from os import listdir
from time import sleep
import os
import csv
import logging
import sys
import ffmpeg
import subprocess
# Logger for logging purposes (seeing which file is currently being processed)
logFormat = "%(levelname)s %(asctime)s - %(message)s"
......@@ -16,50 +14,69 @@ logging.basicConfig(stream = sys.stdout,
format = logFormat,
level = logging.INFO)
# Trims input video file according to interval of timestamps given in CSV.
# Uses ffmpeg-python, which builds a command-line call to ffmpeg that trims parts and finally concatenates them.
# Does NOT delete input video file yet.
def trim(inputVideo, csvTimestamps):
os.chdir("..")
inputPath = os.path.join(os.getcwd(), "input\\{inputVid}".format(inputVid=inputVideo))
outputPath = os.path.join(os.getcwd(), "output\\{outputVid}".format(outputVid=inputVideo))
paddingSecs = 1
movieClip = VideoFileClip(inputVideo)
trims = []
# Pads intervals with an extra second, and checks for edge cases.
for timestampNo in range(0, len(csvTimestamps)-1, 2):
startTime = int(csvTimestamps[timestampNo]) - paddingSecs
endTime = int(csvTimestamps[timestampNo+1]) + paddingSecs
if startTime < 0:
startTime = 0
if endTime > movieClip.duration:
endTime = movieClip.duration
# Removes duplicate intervals (start==end)
dupeClean = []
for timestampNo in range(len(csvTimestamps)-1):
if csvTimestamps[timestampNo] != csvTimestamps[timestampNo+1]:
dupeClean.append(csvTimestamps[timestampNo])
print(dupeClean)
for i in range(len(dupeClean)-1):
# Trims the source video for each interval. 'setpts' filter is used so timestamps are handled correctly; without it,
# still frames will appear in the final video, as it trims based on closest keyframes and fills the gap with stills.
trims.append(ffmpeg.input(inputVideo).trim(start=startTime, end=endTime).filter('setpts', expr='PTS-STARTPTS'))
trims.append(ffmpeg.input(inputPath).trim(start=dupeClean[i], end=dupeClean[i+1]).filter('setpts', expr='PTS-STARTPTS'))
(
ffmpeg
.concat(*trims)
.filter('setpts', expr='PTS-STARTPTS')
.output("output/%s" % inputVideo)
.run(quiet=False)
.output(outputPath)
.run(quiet=True)
)
def doesGroundTruthExist(groundTruthInput):
for file in os.listdir():
if file == groundTruthInput:
return True
else:
return False
def readForCSV(inputVideoName):
os.chdir("input")
if inputVideoName in os.listdir():
# Checks if there is a .csv in the directory. If there is, tries to trim according to timestamps.
# Expects even-sized appropriately timed timestamps in seconds of the input video.
# Example: {5, 33, 106, 180} -> Two intervals of length 28 and 74 seconds respectively.
fileFound = False
videoFound = False
groundTruthName = "groundTruth" + os.path.splitext(inputVideoName)[0] + ".csv"
for file in os.listdir():
if file.endswith(".csv"):
fileFound = True
if file != groundTruthName and file.endswith(".csv"):
videoFound = True
with open(file) as csvFile:
reader = csv.reader(csvFile, delimiter=",")
firstRow = next(reader)
if doesGroundTruthExist(groundTruthName):
# Log instead of print
print("Ground truth file found for video {video}, calculating success rate:".format(video=inputVideoName))
with open(groundTruthName) as truthFile:
truthReader = csv.reader(truthFile, delimiter=",")
# Calculates Jaccard index if ground truth file exists.
Jaccard.calculateSuccess(firstRow, next(truthReader))
# Reads first row only.
trim(inputVideoName, reader.next())
trim(inputVideoName, firstRow)
break
if not fileFound:
if not videoFound:
# Log instead of print.
print("Input video file found, but no .csv file generated or found.")
else:
......
No preview for this file type
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment