from PIL import Image import os

输入文件夹和输出文件夹的路径

input_folder = r'C:\Users\jh\Desktop\data\images_block' output_folder = r'C:\Users\jh\Desktop\data\images_flatten'

确保输出文件夹存在

if not os.path.exists(output_folder): os.makedirs(output_folder)

定义要提取的像素值

pixels_to_extract = [(181, 0, 0), (232, 14, 14), (255, 208, 69), (79, 210, 125)]

定义要替换的像素值和对应的代表值

pixel_replacements = { (181, 0, 0): 4, (232, 14, 14): 3, (255, 208, 69): 2, (79, 210, 125): 1 }

循环遍历输入文件夹中的所有PNG图片

for filename in os.listdir(input_folder): if filename.endswith('.png'): input_path = os.path.join(input_folder, filename)

    # 打开PNG图片并将其转换为RGB模式
    image = Image.open(input_path).convert('RGB')

    # 获取图片的像素值
    pixels = list(image.getdata())

    # 创建空字典用于统计四类像素的数量
    pixel_counts = {pixel: 0 for pixel in pixels_to_extract}

    # 统计四类像素的数量
    for pixel in pixels:
        if pixel in pixel_counts:
            pixel_counts[pixel] += 1

    # 提取指定的像素值并进行替换
    extracted_pixels = [pixel_replacements[pixel] if pixel in pixel_replacements else 0 for pixel in pixels]

    # 将像素值保存到输出文件夹中的文本文件中
    output_path = os.path.join(output_folder, filename.replace('.png', '.txt'))
    with open(output_path, 'w') as file:
        for pixel in extracted_pixels:
            file.write(f'{pixel}\n')

    # 输出当前图片的四类像素的数量
    print(f'{filename}的像素数量统计结果:')
    for pixel, count in pixel_counts.items():
        print(f'{pixel}: {count}')
    print('')

print('转换完成')


原文地址: https://www.cveoy.top/t/topic/Upf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录