| import os |
| import shutil |
| from PIL import Image |
|
|
| def process_and_crop(img_path, output_path): |
| """ |
| Read image, horizontally crop in half (left/right), keep only the left half, and save to output_path. |
| """ |
| if not os.path.exists(img_path): |
| print(f"File does not exist: {img_path}") |
| return False |
| |
| try: |
| with Image.open(img_path) as img: |
| width, height = img.size |
| |
| left_half = img.crop((0, 0, width // 2, height)) |
| left_half.save(output_path) |
| print(f"Successfully saved the cropped left-half image: {output_path}") |
| return True |
| except Exception as e: |
| print(f"Error processing image {img_path}: {e}") |
| return False |
|
|
| def main(): |
| img_label_dir = "skins" |
| control_dir = "control_imgs" |
| |
| if not os.path.exists(img_label_dir): |
| print(f"Error: Directory {img_label_dir} does not exist.") |
| return |
| |
| |
| png_files = sorted([f for f in os.listdir(img_label_dir) if f.lower().endswith(".png")]) |
| |
| processed_count = 0 |
| skipped_count = 0 |
| |
| for filename in png_files: |
| if filename.startswith("half_"): |
| |
| continue |
| |
| |
| half_filename = f"half_{filename}" |
| |
| |
| src_img_label = os.path.join(img_label_dir, filename) |
| dst_img_label = os.path.join(img_label_dir, half_filename) |
| |
| base_name, _ = os.path.splitext(filename) |
| |
| src_control = os.path.join(control_dir, filename) |
| dst_control = os.path.join(control_dir, half_filename) |
| |
| |
| has_control = os.path.exists(src_control) |
| |
| img_label_exists = os.path.exists(dst_img_label) |
| control_exists = not has_control or os.path.exists(dst_control) |
| |
| if img_label_exists and control_exists: |
| skipped_count += 1 |
| continue |
| |
| print(f"\nProcessing {filename}...") |
| processed_count += 1 |
| |
| |
| if img_label_exists: |
| print(f" [Skip] Image {dst_img_label} already exists.") |
| else: |
| try: |
| shutil.copy(src_img_label, dst_img_label) |
| print(f" [Success] Copied image to {dst_img_label}") |
| except Exception as e: |
| print(f" [Error] Failed to copy image to {dst_img_label}: {e}") |
| |
| |
| if has_control: |
| if control_exists: |
| print(f" [Skip] Cropped image {dst_control} already exists.") |
| else: |
| process_and_crop(src_control, dst_control) |
| else: |
| print(f" [Note] No corresponding image {src_control} in control_imgs directory") |
|
|
| print(f"\nProcessing complete! Newly processed {processed_count} pairs, skipped {skipped_count} existing pairs.") |
|
|
| if __name__ == "__main__": |
| main() |
|
|