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 01e9656e5c
Some checks failed
ci/woodpecker/push/lint Pipeline failed
ci/woodpecker/push/test Pipeline failed
Final project demo files
2022-05-28 16:34:46 +01:00

129 lines
No EOL
3.6 KiB
Python

import cv2
import os
from os.path import abspath
import datetime
import matplotlib.pyplot as plt
from tqdm import tqdm
import numpy as np
import random
from PIL import Image
import requests
import json
# 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
def showImage(path):
image = cv2.imread(path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.imshow(image)
plt.show()
def showDiscreteFFT(image):
fftImage = np.fft.fft2(image)
fftShift = np.fft.fftshift(fftImage)
magnitude = 20 * np.log(np.abs(fftShift))
fig = plt.figure(figsize=(15, 6))
fig.add_subplot(1, 2, 1)
plt.imshow(image, cmap="gray")
fig.add_subplot(1, 2, 2)
plt.imshow(magnitude, cmap="gray")
fig.tight_layout()
plt.show()
def loadImageFromURL(url):
response = requests.get(url)
image = Image.open(requests.get(url, stream=True).raw)
return image
def PILToNumpy(image):
image = np.array(image)
return image
def URL2FFT(url):
image = loadImageFromURL(url)
if image.mode == "RGB":
image = PILToNumpy(image)
image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
else:
image = PILToNumpy(image)
showDiscreteFFT(image)
def fileToList(path):
with open(path) as f:
contents = f.read().rstrip()
paths = contents.strip('][').replace("'", "").split(', ')
return paths