File size: 2,329 Bytes
d0e5423
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import os
from PIL import Image

def split_images():
    control_dir = "control_imgs"
    if not os.path.exists(control_dir):
        print(f"Error: Directory '{control_dir}' does not exist.")
        return

    # Define subdirectories for front and back images
    front_dir = os.path.join(control_dir, "front")
    back_dir = os.path.join(control_dir, "back")
    
    # Create the subdirectories if they do not exist
    os.makedirs(front_dir, exist_ok=True)
    os.makedirs(back_dir, exist_ok=True)

    # List all files in the control_imgs directory
    files = os.listdir(control_dir)
    image_extensions = ('.png', '.jpg', '.jpeg', '.webp')
    
    # Filter files: must be a file (not a directory like 'front' or 'back') and have correct extension
    target_files = [
        f for f in files 
        if os.path.isfile(os.path.join(control_dir, f))
        and f.lower().endswith(image_extensions)
    ]
    
    if not target_files:
        print("No target images found to split.")
        return

    print(f"Found {len(target_files)} images to split.")
    
    success_count = 0
    for filename in target_files:
        img_path = os.path.join(control_dir, filename)
        try:
            with Image.open(img_path) as img:
                width, height = img.size
                
                # Split vertically in the middle
                left_half = img.crop((0, 0, width // 2, height))
                right_half = img.crop((width // 2, 0, width, height))
                
                # Define output paths inside subdirectories
                front_path = os.path.join(front_dir, filename)
                back_path = os.path.join(back_dir, filename)
                
                # Save the split images
                left_half.save(front_path)
                right_half.save(back_path)
                
            # Delete the original image after successfully splitting and saving
            os.remove(img_path)
            print(f"Successfully split: {filename} -> front/{filename} and back/{filename}")
            success_count += 1
        except Exception as e:
            print(f"Error processing {filename}: {e}")
            
    print(f"\nProcessing complete! Successfully split {success_count}/{len(target_files)} images.")

if __name__ == "__main__":
    split_images()