File size: 2,296 Bytes
4a5ff1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
66
67
68
69
70
import os
import glob
from multiprocessing import Pool
from PIL import Image


def add_black_layer(image_path):
    """
    Adds a black layer to the image at the given path and saves the modified image.

    This function opens an image, converts it to 'RGBA' mode, creates a new black layer,
    pastes the original image onto the black layer, and saves the result back to the disk.

    Parameters:
    image_path (str): The file path to the image to be processed.

    Raises:
    Exception: If there is an error opening or processing the image.
    """
    print(f"Processing {image_path}...")
    try:
        with Image.open(image_path) as img:
            img = img.convert("RGBA")
            black_layer = Image.new("RGBA", img.size, (0, 0, 0, 255))
            black_layer.paste(img, (0, 0), img)
            black_layer.save(image_path)
            print(f"Black layer added to {image_path}")
    except Exception as e:
        print(f"Error processing {image_path}: {e}")
        raise


def process_image(image_path):
    """
    Processes a single image by adding a black layer.

    This function is designed to be used with multiprocessing. It calls the 'add_black_layer'
    function and handles any exceptions that occur.

    Parameters:
    image_path (str): The file path to the image to be processed.
    """
    try:
        add_black_layer(image_path)
        print(f"Black layer added to and overwritten {image_path}")
    except Exception as e:
        print(f"Error processing {image_path}: {e}")


def process_directory(directory):
    """
    Processes all .png images in a directory by adding a black layer to each.

    This function finds all .png images within the specified directory (including subdirectories),
    then creates a pool of worker processes to process each image in parallel.

    Parameters:
    directory (str): The directory path where the .png images are located.
    """
    image_paths = glob.glob(os.path.join(directory, "**", "*.png"), recursive=True)
    print(f"Found {len(image_paths)} images to process.")
    with Pool() as pool:
        pool.map(add_black_layer, image_paths)


if __name__ == "__main__":
    directory = r"E:\training_dir"
    print(f"Starting processing of images in {directory}")
    process_directory(directory)