Skip to content
Permalink
main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
from PIL import Image
import os
def convert_to_rgb(image_path):
try:
image = Image.open(image_path)
if image.mode == 'RGB':
return image
elif image.mode == 'L':
# Convert grayscale images to RGB
return image.convert('RGB')
elif image.mode == 'P':
# Convert palette images with transparency to RGBA, then to RGB
return image.convert('RGBA').convert('RGB')
else:
return image.convert('RGB')
except Exception as e:
print(f"Error converting image {image_path}: {e}")
return None
def process_images_in_folder(input_folder, output_folder):
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for filename in os.listdir(input_folder):
if filename.endswith(('.png', '.jpg', '.jpeg', '.gif')):
input_image_path = os.path.join(input_folder, filename)
output_image_path = os.path.join(output_folder, filename)
new_image = convert_to_rgb(input_image_path)
if new_image:
new_image.save(output_image_path, 'JPEG')
input_folder = "test"
output_folder = "rgb_test"
process_images_in_folder(input_folder, output_folder)