import json from PIL import Image import os # 全局变量定义分辨率 RESIZE_TO = (256, 256) LARGE_IMAGE_SIZE = (2048, 2048) IMAGE_COUNT = 64 #ROOT_DIR = '../example/src/main/assets/pic' ROOT_DIR = 'D:/face_sdk/example/src/main/assets/pic' def load_json(file_path): with open(file_path, 'r') as file: return json.load(file) def remove_white_border(image): """ 去除图片边缘的一个像素宽的白色边框。 :param image: 输入的PIL Image对象。 :return: 处理后的PIL Image对象。 """ # 获取图像尺寸 width, height = image.size # 定义白色阈值,允许一定的误差范围 white_threshold = (250, 250, 250) # 查找左边界 left = 0 while left < width and all(image.getpixel((left, y))[:3] >= white_threshold for y in range(height)): left += 1 # 查找右边界 right = width - 1 while right > 0 and all(image.getpixel((right, y))[:3] >= white_threshold for y in range(height)): right -= 1 # 查找上边界 top = 0 while top < height and all(image.getpixel((x, top))[:3] >= white_threshold for x in range(width)): top += 1 # 查找下边界 bottom = height - 1 while bottom > 0 and all(image.getpixel((x, bottom))[:3] >= white_threshold for x in range(width)): bottom -= 1 # 如果发现有白色边框,则裁剪它们 if left < right and top < bottom: image = image.crop((left, top, right + 1, bottom + 1)) return image def resize_image(image_path): image = Image.open(image_path).convert('RGBA') image = remove_white_border(image) image = image.resize(RESIZE_TO) return image def main(json_file_path): # 确保使用完整路径 json_file_path = os.path.join(ROOT_DIR, json_file_path) data = load_json(json_file_path) new_data = {} for folder_name, images in data.items(): large_image = Image.new('RGBA', LARGE_IMAGE_SIZE, color=(0, 0, 0, 0)) images_coordinates = {} index = 0 for image_name in images: if index >= IMAGE_COUNT: break # 图片位于子文件夹内 img_path = os.path.join(ROOT_DIR, folder_name, image_name) img = resize_image(img_path) x = (index % 8) * RESIZE_TO[0] y = (index // 8) * RESIZE_TO[1] large_image.paste(img, (x, y)) images_coordinates[image_name] = {'x': x, 'y': y} index += 1 output_image_path = os.path.join(ROOT_DIR, f"{folder_name}ex.png") large_image.save(output_image_path, format='png') # 将坐标信息直接保存到new_data字典中 new_data[folder_name] = images_coordinates # 输出新的json文件 output_json_path = os.path.join(ROOT_DIR, 'motion_data_ex.json') with open(output_json_path, 'w') as outfile: json.dump(new_data, outfile, indent=4) # 使用示例 main('motion_data_ex2.json')