-
Notifications
You must be signed in to change notification settings - Fork 19
/
frameconverter.py
154 lines (145 loc) · 5.56 KB
/
frameconverter.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import cv2
import numpy as np
import os
from os.path import isfile, join
import webuiAPI.generator
from PIL import Image, PngImagePlugin
import logging
import compress
import webuiAPI.setting
MAX_FPS = 60
def format_timedelta(td):
"""Utility function to format timedelta objects in a cool way (e.g 00:00:20.05)
omitting microseconds and retaining milliseconds"""
result = str(td)
try:
result, ms = result.split(".")
except ValueError:
return (result + ".00").replace(":", "-")
ms = int(ms)
ms = round(ms / 1e4)
return f"{result}.{ms:02}".replace(":", "-")
def get_saving_frames_durations(cap, saving_fps):
"""A function that returns the list of durations where to save the frames"""
s = []
# get the clip duration by dividing number of frames by the number of frames per second
clip_duration = cap.get(cv2.CAP_PROP_FRAME_COUNT) / cap.get(cv2.CAP_PROP_FPS)
# use np.arange() to make floating-point steps
for i in np.arange(0, clip_duration, 1 / saving_fps):
s.append(i)
return s
def video2frame(video_file,framepersec=60):
SAVING_FRAMES_PER_SECOND = framepersec
filename, _ = os.path.splitext(video_file)
filename += "-opencv"
# make a folder by the name of the video file
if not os.path.isdir(filename):
os.mkdir(filename)
# read the video file
cap = cv2.VideoCapture(video_file)
if cap.isOpened() == False:
cap.open(video_file)
logging.info(f"open{cap.isOpened()}")
# get the FPS of the video
fps = cap.get(cv2.CAP_PROP_FPS)
# if the SAVING_FRAMES_PER_SECOND is above video FPS, then set it to FPS (as maximum)
saving_frames_per_second = min(fps, SAVING_FRAMES_PER_SECOND)
# get the list of duration spots to save
saving_frames_durations = get_saving_frames_durations(cap, saving_frames_per_second)
# start the loop
count = 0
temp=0
while True:
is_read, frame = cap.read()
if not is_read:
# break out of the loop if there are no frames to read
break
# get the duration by dividing the frame count by the FPS
frame_duration = count / fps
try:
# get the earliest duration to save
closest_duration = saving_frames_durations[0]
except IndexError:
# the list is empty, all duration frames were saved
break
if frame_duration >= closest_duration:
# if closest duration is less than or equals the frame duration,
# then save the frame
cv2.imwrite(os.path.join(filename, f"frame{temp}.png"), frame)
compress.resize_png(os.path.join(filename, f"frame{temp}.png"))
temp=temp+1
# drop the duration spot from the list, since this duration spot is already saved
try:
saving_frames_durations.pop(0)
except IndexError:
pass
# increment the frame count
count += 1
return filename
def interpolation(fps):
pass
'''def frame2video(pathIn,pathOut,fps):
logging.info(f"pathIn: {pathIn}")
logging.info(f"pathOut: {pathOut}")
frame_array = []
files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))]
#for sorting the file names properly
files.sort(key = lambda x: int(x[5:-4]))
for i in range(int(len(files))):
filename=pathIn + files[i]
#reading each files
img = cv2.imread(filename)
print(filename)
#inserting the frames into an image array
frame_array.append(img)
out = cv2.VideoWriter(pathOut,cv2.VideoWriter_fourcc(*'mp4v'), fps, (setup["width"], setup["height"]))
logging.info("HERE TO OUT")
for i in range(len(frame_array)):
# writing to a image array
out.write(frame_array[i])
out.release()'''
def convert_frames_to_video(pathIn,pathOut,fps):
frame_array = []
files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))]
#for sorting the file names properly
files.sort(key = lambda x: int(x[5:-4]))
for i in range(int(len(files))):
filename=pathIn + files[i]
#reading each files3
img = cv2.imread(filename)
height, width, layers = img.shape
size = (width,height)
print(filename)
#inserting the frames into an image array
frame_array.append(img)
out = cv2.VideoWriter(pathOut,cv2.VideoWriter_fourcc(*'mp4v'), fps, size)
for i in range(len(frame_array)):
# writing to a image array
out.write(frame_array[i])
out.release()
def processframes(pathIn, pathOut):
if not os.path.isdir(pathIn):
os.mkdir(pathIn)
files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))]
#for sorting the file names properly
files.sort(key = lambda x: int(x[5:-4]))
temp=0
for i in range(int(len(files))):
logging.info("DEAILING WITH FRAME "+str(i))
filename=pathIn+files[i]
#reading each files
img = Image.open(filename)
height, width = img.width, img.height
webuiAPI.setting.setup["width"]=height
webuiAPI.setting.setup["height"]=width
print(filename)
output = webuiAPI.generator.controlNetImg2img(image=img, setup=webuiAPI.setting.setup)
#inserting the frames into an image array
webuiAPI.generator.saveimg(path=pathOut, img=output, fileName=f"frame{temp}")
temp+=1
logging.info("DEAL FRAME FINISH")
if __name__=="__main__":
import sys
#pathin=sys.argv[1]
#pathout=sys.argv[2]
processframes('D:\StudyLife\Github\HackIllinois\input\girl-44686_4-opencv/', 'output/')