Add close button event

This commit is contained in:
JunHo Kim committed 2021-07-07 15:54:16 +09:00
1 parent 87516fb09f
commit 39bc4bba18
1 file changed
+74 -39
+74 -39
View File
@@ -8,6 +8,7 @@ import glob
import re import re
import subprocess import subprocess
import argparse import argparse
import copy
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input_dir", default="./", help="Input vid directory") parser.add_argument("-i", "--input_dir", default="./", help="Input vid directory")
@@ -20,9 +21,9 @@ def resizeCropInfo(key, cropPos, frame_width, frame_height):
w, h, x, y = _cropPos w, h, x, y = _cropPos
if (w + x) > frame_width or (h + y) > frame_height: if (w + x) > frame_width or (h + y) > frame_height:
return True return True
if not all([a >= 0 for a in [x, y]]): if (x < 0) or (y < 0):
return True return True
if not all([a >= 0 for a in [w, h]]): if (w <= 0) or (h <= 0):
return True return True
w, h, x, y = cropPos w, h, x, y = cropPos
@@ -74,20 +75,17 @@ def main():
for types in vid_types : for types in vid_types :
vid_grapped += sorted(glob.glob(os.path.join(args.input_dir, types))) vid_grapped += sorted(glob.glob(os.path.join(args.input_dir, types)))
# _scale = args.scale.split(":")
# if len(_scale) != 2 :
# print("Invalid target scale : ", args.scale)
# return
# target_width, target_height = [int(x) for x in _scale]
#-------------------------------------------------------- #--------------------------------------------------------
f = io.StringIO() f = io.StringIO()
#-------------------------------------------------------- #--------------------------------------------------------
for fpath in vid_grapped: for fpath in vid_grapped:
# debugging
# fpath = "01. Group S - I Swear MV.avi"
vid_name = os.path.basename(fpath)[:-4] vid_name = os.path.basename(fpath)[:-4]
print("File to detect crop: ", fpath) print("File to detect crop: ", fpath)
p = subprocess.Popen(["ffmpeg", "-ss", "10", "-i", fpath, "-vf", "cropdetect=limit=38", p = subprocess.Popen(["ffmpeg", "-ss", "10", "-i", fpath, "-vf", "cropdetect=limit=38",
"-vframes", "3000", "-f", "null", "out.null"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) "-vframes", "3000", "-f", "null", "out.null"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
@@ -101,9 +99,8 @@ def main():
global crop global crop
crop = mostCommonCrop[0][0] crop = mostCommonCrop[0][0]
cropPos = crop.split(":")
# Delete "crop=" in list cropPos # Delete "crop=" in list cropPos
cropPos = crop.split(":")
cropPos[0] = cropPos[0][5:] cropPos[0] = cropPos[0][5:]
cropPos = [int(x) for x in cropPos] cropPos = [int(x) for x in cropPos]
@@ -112,41 +109,66 @@ def main():
capture = cv2.VideoCapture(fpath) capture = cv2.VideoCapture(fpath)
frame_width = capture.get(cv2.CAP_PROP_FRAME_WIDTH) frame_width = capture.get(cv2.CAP_PROP_FRAME_WIDTH)
frame_height = capture.get(cv2.CAP_PROP_FRAME_HEIGHT) frame_height = capture.get(cv2.CAP_PROP_FRAME_HEIGHT)
frame_count = capture.get(cv2.CAP_PROP_FRAME_COUNT)
fps = capture.get(cv2.CAP_PROP_FPS) fps = capture.get(cv2.CAP_PROP_FPS)
frame_pos = 0 frame_pos = 0
frame_count = 0 frame_count = 0
target_ratio = 16 / 9
target_width, target_height = (frame_width, frame_height) # Crop Area even num check
if not ((target_width > 0) and (target_height > 0)): if (cropPos[0] % 2) != 0 :
print("Invalid target scale : ", target_width, target_height) if (cropPos[0] + 1) >= frame_width:
return cropPos[0] -= 1
else : else:
print("Input dir :", args.input_dir) cropPos[0] += 1
print("Target scale: ", target_width, target_height) if (cropPos[1] % 2) != 0 :
if (cropPos[1] + 1) >= frame_width:
cropPos[1] -= 1
else:
cropPos[1] += 1
print("Target Ratio : %.5f" %target_ratio)
print("Input dir :", args.input_dir)
key = None key = None
isPaused = False
pausedFrame = None
frame = None
cv2.namedWindow(f'{vid_name}')
while True: while True:
key = cv2.waitKeyEx(10) key = cv2.waitKeyEx(10)
# Handle close button event
if cv2.getWindowProperty(f'{vid_name}', cv2.WND_PROP_VISIBLE) < 1 :
return
if key > 0 : if key > 0 :
# 13 == Enter key ASCII Code # 13 == Enter key ASCII Code
if key == 13: if key == 13:
break break
# Pause # Pause
elif key == ord('p') or key == ord('P'): elif key == ord('p') or key == ord('P'):
key = cv2.waitKeyEx() if isPaused :
isPaused = False
else :
isPaused = True
frame = copy.deepcopy(pausedFrame)
# Replay # Replay
elif key == ord('r') or key == ord('R'): elif key == ord('r') or key == ord('R'):
capture = cv2.VideoCapture(fpath) if not isPaused:
continue capture = cv2.VideoCapture(fpath)
continue
# Move Forward (10s) # Move Forward (10s)
elif key == ord('e') or key == ord('E'): elif key == ord('e') or key == ord('E'):
capture.set(cv2.CAP_PROP_POS_FRAMES, frame_pos + (fps * 10)) if not isPaused:
capture.set(cv2.CAP_PROP_POS_FRAMES, frame_pos + (fps * 10))
# Move Backward (10s) # Move Backward (10s)
elif key == ord('q') or key == ord('Q'): elif key == ord('q') or key == ord('Q'):
capture.set(cv2.CAP_PROP_POS_FRAMES, frame_pos - (fps * 10)) if not isPaused:
capture.set(cv2.CAP_PROP_POS_FRAMES, frame_pos - (fps * 10))
else:
cropPos = resizeCropInfo(key, cropPos, frame_width, frame_height) # Crop Area control
cropPos = resizeCropInfo(key, cropPos, frame_width, frame_height)
frame_pos = capture.get(cv2.CAP_PROP_POS_FRAMES) frame_pos = capture.get(cv2.CAP_PROP_POS_FRAMES)
frame_count = capture.get(cv2.CAP_PROP_FRAME_COUNT) frame_count = capture.get(cv2.CAP_PROP_FRAME_COUNT)
@@ -154,12 +176,18 @@ def main():
if(frame_pos >= frame_count): if(frame_pos >= frame_count):
break break
ret, frame = capture.read() if not isPaused:
ret, frame = capture.read()
cv2.rectangle(frame, (cropPos[2], cropPos[3]), (cropPos[2] + cropPos[0], pausedFrame = copy.deepcopy(frame)
cv2.rectangle(frame, (cropPos[2], cropPos[3]), (cropPos[2] + cropPos[0],
cropPos[3] + cropPos[1]), (0, 0, 255), thickness=1, lineType=cv2.LINE_8) cropPos[3] + cropPos[1]), (0, 0, 255), thickness=1, lineType=cv2.LINE_8)
# cv2.rectangle(frame, (4,43), (717,431), (0, 0, 255), thickness=1, lineType=cv2.LINE_8) cv2.imshow(f'{vid_name}', frame)
cv2.imshow(f'{vid_name}', frame) else :
pausedFrame = copy.deepcopy(frame)
cv2.rectangle(pausedFrame, (cropPos[2], cropPos[3]), (cropPos[2] + cropPos[0],
cropPos[3] + cropPos[1]), (0, 0, 255), thickness=1, lineType=cv2.LINE_8)
cv2.imshow(f'{vid_name}', pausedFrame)
capture.release() capture.release()
cv2.destroyAllWindows() cv2.destroyAllWindows()
@@ -168,17 +196,24 @@ def main():
crop_arg = f"crop={cropPos[0]}:{cropPos[1]}:{cropPos[2]}:{cropPos[3]}," crop_arg = f"crop={cropPos[0]}:{cropPos[1]}:{cropPos[2]}:{cropPos[3]},"
print(f"[CropInfo] (W : {cropPos[0]}), (H : {cropPos[1]}), (X : {cropPos[2]}), (Y : {cropPos[3]})") print(f"[CropInfo] (W : {cropPos[0]}), (H : {cropPos[1]}), (X : {cropPos[2]}), (Y : {cropPos[3]})")
target_ratio = target_width / target_height
crop_ratio = cropPos[0] / cropPos[1] crop_ratio = cropPos[0] / cropPos[1]
scale_arg = ""
if target_ratio < crop_ratio: if target_ratio < crop_ratio:
tmp_height = target_width * (cropPos[1] / cropPos[0]) offset = (9 * cropPos[0] - 16 * cropPos[1]) / 16
scale_arg = f"scale=w={target_width}:h={tmp_height}," if int(offset) % 2 != 0:
offset += 1
tmp_height = cropPos[1] + offset
# scale_arg = f"scale=w={cropPos[0]}:h={tmp_height},"
pad_arg = f"pad={cropPos[0]}:{tmp_height}:(ow-iw)/2:(ih-oh)/2,"
else: else:
tmp_width = target_height * (cropPos[0] / cropPos[1]) offset = (16 * cropPos[1] - 9 * cropPos[0]) / 9
scale_arg = f"scale=w={tmp_width}:h={target_height}," if int(offset) % 2 != 0:
offset += 1
tmp_width = cropPos[0] + offset
# scale_arg = f"scale=w={tmp_width}:h={cropPos[1]},"
pad_arg = f"pad={tmp_width}:{cropPos[1]}:(ow-iw)/2:(ih-oh)/2,"
pad_arg = f"pad={target_width}:{target_height}:(ow-iw)/2:(ih-oh)/2,"
print("Encoding \"%s\" ..." % vid_name) print("Encoding \"%s\" ..." % vid_name)
@@ -190,10 +225,10 @@ def main():
if args.debug: if args.debug:
# for Debug # for Debug
p = subprocess.Popen(["ffmpeg", "-t", "15", "-ss", "30", "-i", fpath, "-vf", crop_arg + scale_arg + pad_arg + "setsar=sar=1", "-y", p = subprocess.Popen(["ffmpeg", "-t", "15", "-ss", "30", "-i", fpath, "-vf", crop_arg + scale_arg + pad_arg + "setsar=sar=1", "-y",
"-pix_fmt", "yuv420p", "-c:v", "libx264", "-crf", "15", "-preset", "medium", "-loglevel", "error", f"{output_path}"]) "-pix_fmt", "yuv420p", "-c:v", "libx264", "-crf", "0", "-preset", "medium", "-loglevel", "error", f"{output_path}"])
else: else:
p = subprocess.Popen(["ffmpeg", "-i", fpath, "-vf", crop_arg + scale_arg + pad_arg + "setsar=sar=1", "-y", "-pix_fmt", p = subprocess.Popen(["ffmpeg", "-i", fpath, "-vf", crop_arg + scale_arg + pad_arg + "setsar=sar=1", "-y", "-pix_fmt",
"yuv420p", "-c:v", "libx264", "-crf", "15", "-preset", "medium", "-loglevel", "error", f"{output_path}"]) "yuv420p", "-c:v", "libx264", "-crf", "0", "-preset", "medium", "-loglevel", "error", f"{output_path}"])
print("Encoding Done.") print("Encoding Done.")