75 lines
2.1 KiB
Python
75 lines
2.1 KiB
Python
import os
|
|
import cv2
|
|
|
|
# ----------------------------
|
|
# 配置
|
|
# ----------------------------
|
|
SOURCE_ROOT_DIR = "/media/hx/04e879fa-d697-4b02-ac7e-a4148876ebb0/dataset/cls-61/class4"
|
|
TARGET_ROOT_DIR = "/media/hx/04e879fa-d697-4b02-ac7e-a4148876ebb0/dataset/cls-61/class4c"
|
|
TARGET_SIZE = 640 # resize 尺寸
|
|
|
|
# ----------------------------
|
|
# 全局 ROI (x, y, w, h)
|
|
# ----------------------------
|
|
GLOBAL_ROI = [445, 540, 931, 319]
|
|
#GLOBAL_ROI = [604, 182, 594, 252]
|
|
|
|
|
|
# ----------------------------
|
|
# 主处理函数
|
|
# ----------------------------
|
|
def process_images():
|
|
x, y, w, h = GLOBAL_ROI
|
|
|
|
# 遍历主目录下的所有子文件夹
|
|
for sub_dir_name in sorted(os.listdir(SOURCE_ROOT_DIR)):
|
|
src_sub_dir = os.path.join(SOURCE_ROOT_DIR, sub_dir_name)
|
|
|
|
if not os.path.isdir(src_sub_dir):
|
|
continue # 跳过非文件夹
|
|
|
|
tgt_sub_dir = os.path.join(TARGET_ROOT_DIR, sub_dir_name)
|
|
os.makedirs(tgt_sub_dir, exist_ok=True)
|
|
|
|
print(f"\n📁 处理文件夹: {sub_dir_name}")
|
|
|
|
for file in os.listdir(src_sub_dir):
|
|
if not file.lower().endswith((".jpg", ".png", ".jpeg", ".bmp", ".tif", ".tiff")):
|
|
continue
|
|
|
|
img_path = os.path.join(src_sub_dir, file)
|
|
img = cv2.imread(img_path)
|
|
|
|
if img is None:
|
|
print(f"❌ 无法读取图片: {img_path}")
|
|
continue
|
|
|
|
h_img, w_img = img.shape[:2]
|
|
|
|
# ROI 边界保护
|
|
x1 = max(0, x)
|
|
y1 = max(0, y)
|
|
x2 = min(w_img, x + w)
|
|
y2 = min(h_img, y + h)
|
|
|
|
cropped = img[y1:y2, x1:x2]
|
|
if cropped.size == 0:
|
|
print(f"❌ 裁剪结果为空: {img_path}")
|
|
continue
|
|
|
|
resized = cv2.resize(cropped, (TARGET_SIZE, TARGET_SIZE), interpolation=cv2.INTER_AREA)
|
|
|
|
tgt_path = os.path.join(tgt_sub_dir, file)
|
|
cv2.imwrite(tgt_path, resized)
|
|
|
|
print(f"✅ {sub_dir_name}/{file}")
|
|
|
|
print("\n🎉 全部图片处理完成")
|
|
|
|
|
|
# ----------------------------
|
|
# 入口
|
|
# ----------------------------
|
|
if __name__ == "__main__":
|
|
process_images()
|