diff --git a/tools/CropRoi/main.py b/tools/CropRoi/main.py index 247bf19..3eed29e 100644 --- a/tools/CropRoi/main.py +++ b/tools/CropRoi/main.py @@ -1,15 +1,14 @@ import cv2 import os - +from typing import List, Tuple print("Usage:\n" "Put the 16:9 images under ./src, and run this script, it will be auto converted to 720p.\n" "Drag mouse to select ROI, press 'S' to save, press 'Q' to quit.\n" "The cropped images will be saved in ./dst\n") - # 初始化参考点列表和布尔值标志:是否正在执行裁剪 -refPt = [] +refPt: List[Tuple[int, int]] = [] cropping = False @@ -18,8 +17,9 @@ # -x x坐标 # -y y坐标 # -flages params 其他参数 -def click_and_crop(event, x, y, flags, param): +def click_and_crop(event: int, x: int, y: int, *args) -> None: # 获取全局变量的引用 + global refPt, cropping # 如果鼠标左被单击,记录(x,y)坐标并显示裁剪正在进行 @@ -45,20 +45,20 @@ def click_and_crop(event, x, y, flags, param): cv2.setMouseCallback("image", click_and_crop) for filename in os.listdir("./src"): - if not filename.endswith(".png"): + if not (filename.endswith(".png") or filename.endswith(".jpg")): continue print("src:", filename) - image = cv2.imread("./src/" + filename) + image = cv2.imread(f"./src/{filename}") cur_ratio = image.shape[1] / image.shape[0] - if cur_ratio >= std_ratio: # 说明是宽屏或默认16:9,按照高度计算缩放 - dsize_width: int = (int)(cur_ratio * std_height) - dsize_height: int = std_height - else: # 否则可能是偏正方形的屏幕,按宽度计算 - dsize_width: int = std_width - dsize_height: int = std_width / cur_ratio + if cur_ratio >= std_ratio: + dsize_width = int(cur_ratio * std_height) + dsize_height = std_height + else: + dsize_width = std_width + dsize_height = int(std_width / cur_ratio) dsize = (dsize_width, dsize_height) image = cv2.resize(image, dsize, interpolation=cv2.INTER_AREA) @@ -85,12 +85,10 @@ def click_and_crop(event, x, y, flags, param): horizontal_expansion = 100 vertical_expansion = 100 - filename_x: int = (int)(left - horizontal_expansion / 2) - if filename_x < 0: - filename_x = 0 - filename_y: int = (int)(top - vertical_expansion / 2) - if filename_y < 0: - filename_y = 0 + filename_x: int = int(left - horizontal_expansion / 2) + filename_x = max(filename_x, 0) + filename_y: int = int(top - vertical_expansion / 2) + filename_y = max(filename_y, 0) filename_w: int = (right - left) + horizontal_expansion if filename_x + filename_w > dsize_width: filename_w = dsize_width - filename_x @@ -104,9 +102,9 @@ def click_and_crop(event, x, y, flags, param): print(f"original roi: {left}, {top}, {right - left}, {bottom - top}, \n" f"amplified roi: {filename_x}, {filename_y}, {filename_w}, {filename_h}\n\n") - cv2.imwrite('./dst/' + dst_filename, roi) + cv2.imwrite(f'./dst/{dst_filename}', roi) - refPt = [] + refPt: List[Tuple[int, int]] = [] cropping = False # 关闭所有打开的窗口