PaulZjy's picture
Upload 194 files
fa213f2 verified
Raw
History Blame Contribute Delete
1.47 kB
# crop_left_512.py
import os
from PIL import Image
INPUT_DIR = "./picture" # 原图文件夹
OUTPUT_DIR = "./picture_resized" # 输出文件夹
TARGET_H = 1536 # 目标高度(像素)
CROP_W = 512 # 只保留左侧 [0, 512) 宽度
os.makedirs(OUTPUT_DIR, exist_ok=True)
def is_img(name):
return name.lower().endswith((".jpg", ".jpeg", ".png", ".bmp", ".webp", ".tif", ".tiff"))
for fname in os.listdir(INPUT_DIR):
if not is_img(fname):
continue
src = os.path.join(INPUT_DIR, fname)
dst = os.path.join(OUTPUT_DIR, fname)
try:
with Image.open(src) as im:
im = im.convert("RGB")
# 1) 若高度不是 1536,先按比例把高度调整到 1536(宽度等比变化)
if im.height != TARGET_H:
new_w = round(im.width * TARGET_H / im.height)
im = im.resize((new_w, TARGET_H), Image.BICUBIC)
# 2) 若宽度不足 512,跳过并提示;否则裁剪左侧 0~512 宽度
if im.width < CROP_W:
print(f"[SKIP] {fname}: width {im.width} < {CROP_W}")
continue
left_crop = im.crop((0, 0, CROP_W, TARGET_H)) # (left, top, right, bottom)
left_crop.save(dst)
print(f"[OK] {fname} -> {dst}")
except Exception as e:
print(f"[ERR] {fname}: {e}")
print("✅ 完成:已将左侧 0-512 宽度裁剪并输出到", OUTPUT_DIR)