This repository has been archived on 2022-07-15. You can view files and clone it, but cannot push or open issues or pull requests.
mmp-osp1/docs/project-demo/demo-material/helper-functions.py
Oscar Pocock 9949125a5d
Some checks failed
ci/woodpecker/push/lint Pipeline failed
ci/woodpecker/push/test Pipeline failed
Add demo material
2022-05-16 14:02:40 +01:00

82 lines
No EOL
2.4 KiB
Python

import cv2
import os
from os.path import abspath
import datetime
import matplotlib.pyplot as plt
from tqdm import tqdm
import random
# Export's video frames
def video_to_frames(path):
print("[INFO] Loading video...")
basename = os.path.splitext(os.path.split(path)[1])[0]
output_dir_name = basename + "_frames"
output_dir = os.path.join(os.path.split(path)[0], output_dir_name)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
else:
print("[INFO] Outut folder \"{}\" already exists".format(output_dir))
return
stream = cv2.VideoCapture(path)
count = 0
print("[INFO] Reading and saving frames...")
while True:
(retrieved, frame) = stream.read()
if not retrieved:
break
count += 1
filename = "frame-{}.jpg".format(count)
path = os.path.abspath(os.path.join(output_dir, filename))
cv2.imwrite(path, frame)
print("[INFO] Frames saved to \"{}\"".format(output_dir))
# Plot images
def plot_images(paths):
# plot the images
number_of_images = len(paths)
if number_of_images % 5 == 0:
row = number_of_images // 5
else:
row = (number_of_images // 5) + 1
column = 5
width = 250
size = width * row
outputDir = os.path.join(os.path.dirname(__name__), "output")
fileName = datetime.datetime.now().strftime("%G-%m-%dT%H%M%S") + ".png"
filePath = os.path.join(outputDir, fileName)
if not os.path.exists(outputDir):
os.makedirs(outputDir)
heightOfFig = 6 * row
fig = plt.figure(figsize=(15, heightOfFig))
# Plot the 5 highest on the first row
plotIndex = 1
for path in tqdm(paths):
image = cv2.imread(path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
height = int(image.shape[0] * (width / image.shape[0]))
image = cv2.resize(image, (width, height))
fig.add_subplot(row, column, plotIndex)
plt.imshow(image)
plt.axis('off')
plt.title(os.path.split(path)[1])
plt.tight_layout()
plotIndex += 1
fig.tight_layout()
plt.savefig(filePath)
def list_dir_abs(directory):
dirAbsPath = os.path.abspath(directory)
listOfItems = os.listdir(directory)
listOfPaths = []
for item in listOfItems:
path = os.path.join(dirAbsPath, item)
listOfPaths.append(path)
return listOfPaths
def pickRandomNum(paths, num):
ranPaths = random.choices(paths, k=num)
return ranPaths