Some basic image preprocessing—normalize the scale of all pictures in a file, view the RGB value of each pixel, switch the specified color to white, and switch all pictures in the file from png to jpg

Table of Contents

1. Normalize the scale of all pictures in a file

2. View the RGB value of each pixel of an image

3. Switch the specified color to other colors (switch red to white in the code)

4. Switch all pictures in a file from png to jpg

5. Rename all images in a folder starting from 1

1. Normalize the scale of all pictures in a file

In the example, this code normalizes all images to 352*352. You can adjust the parameters and switch the file address to the file address to be processed.

from PIL import Image
import os


def resize_images(folder_path, output_size):
    # Get all files in the folder
    file_list = os.listdir(folder_path)

    for file_name in file_list:
        # Check whether the file is an image file (conditions can be modified as needed)
        if file_name.endswith(('.jpg', '.jpeg', '.png')):
            file_path = os.path.join(folder_path, file_name)

            # Open and resize the image
            image = Image.open(file_path)
            resized_image = image.resize(output_size)

            # Save the resized image
            resized_image.save(file_path)

            print(f"Resized image: {file_name}")


# Specify the folder path and output size to be processed
folder_path = './TrainDate/masks' # Replace with actual folder path
output_size = (352, 352) # Replace with the desired output size

# Call the function to normalize the image size
resize_images(folder_path, output_size)

2. View the RGB value of each pixel of a picture

from PIL import Image

def get_image_rgb_values(image_path):
    #Open image
    image = Image.open(image_path)

    # Convert the image to RGB mode (ignoring transparency)
    image = image.convert('RGB')

    # Get the pixel data of the image
    pixels = image.load()
    width, height = image.size

    # Iterate through each pixel
    for x in range(width):
        for y in range(height):
            r, g, b = pixels[x, y]
            # Output RGB values
            print(f"Pixel at ({x}, {y}): R={r}, G={g}, B={b}")

    # Close image
    image.close()

#Specify image path
image_path = '1.png'

# Call the function to view the RGB value of the image
get_image_rgb_values(image_path)

3. Switch the specified color to other colors (switch red to white in the code)

Changing to the specified color requires modifying the following code parameters:

# Determine whether it is a red area (the threshold can be adjusted as needed)
if r > 100 and g >100 and b <100:
# Replace the red area with white 0
pixels[x, y] = (255, 255, 255, a)

from PIL import Image
import os

def replace_red_with_white(folder_path):
    # Get all file names in the folder
    filenames = os.listdir(folder_path)
    # Select all PNG image files
    image_files = [filename for filename in filenames if filename.endswith('.png')]

    # Traverse each image file and process it
    for image_file in image_files:
        image_path = os.path.join(folder_path, image_file)
        #Open image
        image = Image.open(image_path)

        # Convert the image to RGBA mode
        image = image.convert('RGBA')

        # Get the pixel data of the image
        pixels = image.load()
        width, height = image.size

        # Iterate through each pixel
        for x in range(width):
            for y in range(height):
                r, g, b, a = pixels[x, y]

                # Determine whether it is a red area (the threshold can be adjusted as needed)
                if r > 100 and g >100 and b <100:
                    # Replace the red area with white 0
                    pixels[x, y] = (255, 255, 255, a)

        # Save the modified image
        new_image_path = os.path.join(folder_path, image_file)
        image.save(new_image_path)

        # Close image
        image.close()

        print(f"Processed {image_file} and saved as {os.path.basename(new_image_path)}")

#Specify folder path
folder_path = './TrainData/masks'

#Call function for processing
replace_red_with_white(folder_path)

The rendering is as follows:

4. Switch all pictures in a file from png to jpg

from PIL import Image
import os

def convert_png_to_jpg(input_folder, output_folder):
    # Iterate through all files in the input folder
    for filename in os.listdir(input_folder):
        if filename.endswith(".png"):
            # Path to build input and output files
            input_path = os.path.join(input_folder, filename)
            output_filename = os.path.splitext(filename)[0] + ".jpg"
            output_path = os.path.join(output_folder, output_filename)

            # Open the PNG image and save it as JPG format
            image = Image.open(input_path)
            image.convert("RGB").save(output_path, "JPEG")
            print(f"Converted {input_path} to {output_path}")

#Specify the paths to the input folder and output folder
input_folder = "input_folder"
output_folder = "output_folder"

# Call function to convert
convert_png_to_jpg(input_folder, output_folder)

5. Rename all images in a folder starting from 1

import os

def rename_images(folder_path):
    # Get all files in the target folder
    file_list = os.listdir(folder_path)
    image_extensions = ['.jpg', '.jpeg', '.png', '.gif'] # Supported image file extensions

    # Filter out image files
    image_files = [file for file in file_list if os.path.splitext(file)[1].lower() in image_extensions]

    # Rename image file
    for i, image_file in enumerate(image_files):
        extension = os.path.splitext(image_file)[1]
        new_name = str(i + 1) + extension
        old_path = os.path.join(folder_path, image_file)
        new_path = os.path.join(folder_path, new_name)
        os.rename(old_path, new_path)
        print(f"{image_file} is renamed to {new_name}")

# Call example
folder_path = "./TrainDataset/image"
rename_images(folder_path)