-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreprocess.py
70 lines (57 loc) · 2.01 KB
/
preprocess.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from tensorflow.keras.preprocessing.image import img_to_array, load_img
import numpy as np
import glob
import os
from PIL import Image
import argparse
imagestore = []
parser = argparse.ArgumentParser(description='Source Video path')
parser.add_argument('source_vid_path', type=str)
parser.add_argument('fps', type=int)
args = parser.parse_args()
video_source_path = args.source_vid_path
fps = args.fps
def create_dir(path):
if not os.path.exists(path):
os.makedirs(path)
def remove_old_images(path):
filelist = glob.glob(os.path.join(path, "*.png"))
for f in filelist:
os.remove(f)
def resize_image(image, target_size):
img = Image.fromarray(image.astype('uint8'))
img = img.resize(target_size)
return np.array(img)
def store(image_path):
img = load_img(image_path)
img = img_to_array(img)
# Resize the Image to (227, 227, 3) using NumPy
img = resize_image(img, (227, 227))
# Convert the Image to Grayscale
gray = 0.2989 * img[:, :, 0] + 0.5870 * img[:, :, 1] + 0.1140 * img[:, :, 2]
imagestore.append(gray)
# List of all Videos in the Source Directory.
videos = os.listdir(video_source_path)
print("Found ", len(videos), " training video")
# Make a temp dir to store all the frames
create_dir(video_source_path + '/frames')
# Remove old images
remove_old_images(video_source_path + '/frames')
framepath = video_source_path + '/frames'
for video in videos:
os.system('ffmpeg -i {}/{} -r 1/{} {}/frames/%03d.jpg'.format(video_source_path, video, fps, video_source_path))
images = os.listdir(framepath)
for image in images:
image_path = framepath + '/' + image
store(image_path)
imagestore = np.array(imagestore)
a, b, c = imagestore.shape
# Reshape to (227, 227, batch_size)
imagestore.resize(b, c, a)
# Normalize
imagestore = (imagestore - imagestore.mean()) / (imagestore.std())
# Clip negative Values
imagestore = np.clip(imagestore, 0, 1)
np.save('training.npy', imagestore)
# Remove Buffer Directory
os.system('rm -r {}'.format(framepath))