This code is for beginners to use, we refer to a lot of code on the Internet, thank the predecessors for their contributions.
The goal of this code is to modify the resolution of all the pictures to 128*128. While modifying the images, it will not elongate them, but supplement the deformed part by filling pure white(any color can be fill by change RGB), which is conducive to the training of GAN.
The code is python, can be copied later debugging use.
Thanks for xinggui.
The last part 【cut_images('F:/date/JPG128enhance/', 'new', 128, 128)】is the target folder you want to enhance.
And 128 represents the image resolution that needs to be modified. For example, 128, 128 represents a picture with a resolution of 128*128, if you need other picture resolutions, you can modify it yourself.
The way for beginners to use is to copy this code into vscode, modify the address of the target directory, save it as a .py file, and then click the small triangle in the upper right corner to run the code.
# -*- coding: utf-8 -*- from PIL import Image from skimage import data_dir,io,transform,color import numpy as np import os def cut_images(dir_path, suffix, aspect_width, aspect_height): images = [os.path.join(dir_path, img) for img in os.listdir(dir_path)] for image in images: cut_image(image, suffix, aspect_width, aspect_height) def cut_image(image_file, suffix, aspect_width, aspect_height): img = Image.open(image_file) img_width = img.size[0] img_height = img.size[1] if (img_width / img_height) > (aspect_width / aspect_height): rate = aspect_width / img_width else: rate = aspect_height / img_height rate = round(rate, 1) img = img.resize((int(img_width * rate), int(img_height * rate))) result_image = Image.new("RGB", [aspect_width, aspect_height], (255, 255, 255, 255)) result_image.paste(img, (int((aspect_width - img.size[0]) / 2), int((aspect_height - img.size[1]) / 2))) save_img, extenstion = os.path.splitext(image_file) result_image.save(save_img + '_' + suffix + extenstion) print('[Done] '+image_file) if __name__ == "__main__": cut_images('F:/date/JPG128enhance/', 'new', 128, 128)
After running, if an error occurs: ModuleNotFoundError: No module named 'PIL'
Please run the code :pip install image
If an error occurs:ModuleNotFoundError: No module named 'skimage'
Run the pip install:scikit-image command
It means you need to install the library, just install it
When there is a [Done] C: / / XXX XXXX/XXXXXXXX/XXXXXXX/XXXX /XXXXXXX.JPG
This means that the code has run successfully and a new image with the _new suffix will be generated inside the original folder