使用方法:首先在代码同级目录创建input_images文件夹,然后将需要转换的图片放进去。
然后根据你的需要,修改代码最下面的crop_size、resize以及file_name。
最后点击运行,即可得到图片的rgb565格式数据
from PIL import Image, ImageOps
import os
import numpy as npdef resize_images(input_folder, output_folder, size):"""批量修改指定文件夹中的图片尺寸,并将Resize后的图片保存到另一个文件夹中。:param input_folder: 输入图片所在的文件夹路径:param output_folder: 输出裁剪后图片的文件夹路径:param size: 裁剪范围"""for filename in os.listdir(input_folder):if filename.endswith(".jpg") or filename.endswith(".png"):img = Image.open(os.path.join(input_folder, filename))img_resized = ImageOps.fit(img, size)img_resized.save(os.path.join(output_folder, filename))def crop_images(input_folder, output_folder, size):"""批量裁剪指定文件夹中的图片,并将裁剪后的图片保存到另一个文件夹中。:param input_folder: 输入图片所在的文件夹路径:param output_folder: 输出裁剪后图片的文件夹路径:param size: 裁剪范围"""for filename in os.listdir(input_folder):if filename.endswith(".jpg") or filename.endswith(".png"):img = Image.open(os.path.join(input_folder, filename))cropped_img = img.crop((size[0], size[1], size[2], size[3]))cropped_img.save(os.path.join(output_folder, filename))def rgb565_to_uint16(r, g, b):return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3)def generate_image_data(folder_path, image_name):image_files = [f for f in os.listdir(folder_path) if f.endswith('.jpg') or f.endswith('.png')]data = []for file in image_files:img = Image.open(os.path.join(folder_path, file))image_name.append(os.path.splitext(file)[0])img = img.convert('RGB')width, height = img.sizeimage_data = np.zeros((height, width), dtype=np.uint16)for y in range(height):for x in range(width):r, g, b = img.getpixel((x, y))image_data[y][x] = rgb565_to_uint16(r, g, b)data.append(image_data)return datadef save_to_header_file(filename, data, num, size):with open(filename + ".h", 'w') as c_file:c_file.write("#include <pgmspace.h>\n\n")c_file.write("// Image name order:\n")for name in image_name:c_file.write(f"// {name}\n")c_file.write(f"const size_t image_size = {num};\n\n")c_file.write(f"const uint16_t PROGMEM image[][{size[0]*size[1]}")c_file.write("] = {\n")for index in range(0, num):c_file.write("{")for row in data[index]:for value in row:c_file.write(f"0x{value:04X}, ")c_file.write("},\n")c_file.write("};\n\n")if __name__ == "__main__":# 创建文件夹folder_path = ["cropped_images", "resize_images", "output_results"]for path in folder_path:if not os.path.exists(path):os.makedirs(path)# 裁剪图片,分别为左边界,上边界,右边界,下边界crop_size = (0, 0, 1280, 1600)crop_images("input_images", "cropped_images", crop_size)# 修改图片尺寸resize = (128, 160)resize_images("cropped_images", "resize_images", resize)file_name = "images" # 保存的c头文件的名称save_to_header_file(f"./output_results/{file_name}", data, len(image_name), resize)