File size: 1,687 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 |
import os
import glob
import multiprocessing
from PIL import Image
# Set the maximum number of pixels allowed in an image to prevent DecompressionBombWarning.
Image.MAX_IMAGE_PIXELS = 139211472
def convert_rgba_to_rgb(image_path):
"""
Convert an RGBA image to RGB format.
"""
try:
print(f"Opening image: {image_path}")
with Image.open(image_path) as image:
print(f"Image mode: {image.mode}")
if image.mode == "RGBA":
rgb_image = image.convert("RGB")
rgb_image.save(image_path)
print(f"Converted {image_path} to RGB.")
else:
print(f"{image_path} is not an RGBA image.")
except Exception as e:
print(f"Error processing {image_path}: {e}")
def main():
"""
Main function to convert all RGBA images to RGB in a directory.
"""
directory = r"E:\training_dir"
print(f"Directory set to: {directory}")
# Get all .png files in the directory recursively
files = glob.glob(os.path.join(directory, "**", "*.png"), recursive=True)
print(f"Found {len(files)} .png files in directory and subdirectories.")
# Determine the number of processes based on the available CPUs
num_processes = multiprocessing.cpu_count()
print(f"Number of processes set to the number of available CPUs: {num_processes}")
# Create a pool of processes
with multiprocessing.Pool(num_processes) as pool:
print("Pool of processes created.")
# Map the convert_rgba_to_rgb function to the files
pool.map(convert_rgba_to_rgb, files)
print("Conversion complete.")
if __name__ == "__main__":
main()
|