Video-Summary/Application/Exporter.py

174 lines
6.9 KiB
Python
Raw Normal View History

import pickle
import time
2020-12-26 13:58:58 +00:00
from datetime import datetime
import cv2
import imageio
2020-09-25 17:52:41 +00:00
import imutils
import numpy as np
from Application.VideoReader import VideoReader
2020-12-26 13:58:58 +00:00
2020-09-20 20:01:54 +00:00
class Exporter:
fps = 30
2020-09-24 13:47:49 +00:00
2020-10-11 15:09:49 +00:00
def __init__(self, config):
self.footagePath = config["inputPath"]
self.outputPath = config["outputPath"]
self.resizeWidth = config["resizeWidth"]
self.config = config
print("Exporter initiated")
2020-09-24 13:47:49 +00:00
def export(self, layers, contours, masks, raw=True, overlayed=True, blackBackground=False, showProgress=False):
2020-10-23 22:14:43 +00:00
if raw:
self.exportRawData(layers, contours, masks)
2020-11-08 15:28:47 +00:00
if overlayed:
self.exportOverlayed(layers, blackBackground, showProgress)
2020-11-08 15:28:47 +00:00
else:
self.exportLayers(layers)
2020-09-25 17:52:41 +00:00
2020-11-11 17:37:25 +00:00
def exportLayers(self, layers):
2020-10-11 12:13:27 +00:00
listOfFrames = self.makeListOfFrames(layers)
with VideoReader(self.config, listOfFrames) as videoReader:
underlay = cv2.VideoCapture(self.footagePath).read()[1]
underlay = cv2.cvtColor(underlay, cv2.COLOR_BGR2RGB)
fps = videoReader.getFPS()
writer = imageio.get_writer(self.outputPath, fps=fps)
start = time.time()
for i, layer in enumerate(layers):
print(f"\r {i}/{len(layers)} {round(i/len(layers)*100,2)}% {round((time.time() - start), 2)}s", end="\r")
if len(layer.bounds[0]) == 0:
continue
videoReader = VideoReader(self.config)
listOfFrames = self.makeListOfFrames([layer])
videoReader.fillBuffer(listOfFrames)
while not videoReader.videoEnded():
frameCount, frame = videoReader.pop()
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame2 = np.copy(underlay)
for (x, y, w, h) in layer.bounds[frameCount - layer.startFrame]:
if x is None:
continue
factor = videoReader.w / self.resizeWidth
x, y, w, h = (int(x * factor), int(y * factor), int(w * factor), int(h * factor))
frame2[y : y + h, x : x + w] = np.copy(frame[y : y + h, x : x + w])
self.addTimestamp(frame2, videoReader, frameCount, layer, x, y, w, h)
writer.append_data(frame2)
writer.close()
def exportOverlayed(self, layers, blackBackground=False, showProgress=False):
2020-10-11 15:09:49 +00:00
listOfFrames = self.makeListOfFrames(layers)
2020-09-30 17:22:10 +00:00
maxLength = self.getMaxLengthOfLayers(layers)
if blackBackground:
underlay = np.zeros(shape=[videoReader.h, videoReader.w, 3], dtype=np.uint8)
else:
underlay = cv2.VideoCapture(self.footagePath).read()[1]
underlay = cv2.cvtColor(underlay, cv2.COLOR_BGR2RGB)
frames = []
for i in range(maxLength):
frames.append(np.copy(underlay))
with VideoReader(self.config, listOfFrames) as videoReader:
while not videoReader.videoEnded():
frameCount, frame = videoReader.pop()
if frameCount % (60 * self.fps) == 0:
print("Minutes processed: ", frameCount / (60 * self.fps), end="\r")
if frame is None:
print("ContourExtractor: frame was None")
continue
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
for layer in layers:
if layer.startFrame <= frameCount and layer.startFrame + len(layer.bounds) > frameCount:
for i in range(0, len(layer.bounds[frameCount - layer.startFrame])):
try:
x, y, w, h = layer.bounds[frameCount - layer.startFrame][i]
if None in (x, y, w, h):
break
factor = videoReader.w / self.resizeWidth
x, y, w, h = (int(x * factor), int(y * factor), int(w * factor), int(h * factor))
mask = self.getMask(i, frameCount, layer, w, h)
background = frames[frameCount - layer.startFrame + layer.exportOffset]
self.addMaskedContent(frame, x, y, w, h, mask, background)
frames[frameCount - layer.startFrame + layer.exportOffset] = np.copy(background)
if showProgress:
cv2.imshow("changes x", background)
cv2.waitKey(10) & 0xFF
self.addTimestamp(frames[frameCount - layer.startFrame + layer.exportOffset], videoReader, frameCount, layer, x, y, w, h)
except:
continue
writer = imageio.get_writer(self.outputPath, fps=videoReader.getFPS())
for frame in frames:
writer.append_data(frame)
writer.close()
2020-09-30 17:22:10 +00:00
def addMaskedContent(self, frame, x, y, w, h, mask, background):
maskedFrame = np.copy(
cv2.bitwise_and(
background[y : y + h, x : x + w],
background[y : y + h, x : x + w],
mask=cv2.bitwise_not(mask),
)
)
background[y : y + h, x : x + w] = cv2.addWeighted(
maskedFrame,
1,
np.copy(cv2.bitwise_and(frame[y : y + h, x : x + w], frame[y : y + h, x : x + w], mask=mask)),
1,
0,
)
def addTimestamp(self, frame, videoReader, frameCount, layer, x, y, w, h):
time = datetime.fromtimestamp(int(frameCount / self.fps) + videoReader.getStartTime())
cv2.putText(
frame,
f"{time.hour}:{time.minute}:{time.second}",
(int(x + w / 2), int(y + h / 2)),
cv2.FONT_HERSHEY_SIMPLEX,
1,
(255, 255, 255),
2,
)
def getMask(self, i, frameCount, layer, w, h):
mask = layer.masks[frameCount - layer.startFrame][i]
mask = imutils.resize(mask, width=w, height=h + 1)
mask = np.resize(mask, (h, w))
mask = cv2.erode(mask, None, iterations=10)
mask *= 255
return mask
def exportRawData(self, layers, contours, masks):
2020-11-08 15:28:47 +00:00
with open(self.config["importPath"], "wb+") as file:
2020-11-27 00:06:25 +00:00
pickle.dump((layers, contours, masks), file)
2020-12-26 13:58:58 +00:00
2020-09-30 17:22:10 +00:00
def getMaxLengthOfLayers(self, layers):
maxLength = 0
for layer in layers:
if layer.getLength() > maxLength:
maxLength = layer.getLength()
return maxLength
def makeListOfFrames(self, layers):
2022-01-09 19:25:44 +00:00
"""Returns set of all Frames which are relavant to the Layers"""
frameNumbers = set()
for layer in layers:
2022-01-09 19:25:44 +00:00
frameNumbers.update(list(range(layer.startFrame, layer.startFrame + len(layer))))
2020-10-19 19:35:15 +00:00
return sorted(list(frameNumbers))