Python 使用 PIL 库将图像像素值转换为数字代码
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): 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

        # 提取指定的像素值并替换其他像素为(0, 0, 0)
        extracted_pixels = [(pixels_to_extract.get(pixel, 0), 0, 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[0]}, {pixel[1]}, {pixel[2]}
')

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

print('转换完成')

代码解释:

  1. 使用os.listdir()函数获取输入文件夹中的所有文件。
  2. 使用filename.endswith('.png')判断文件是否为PNG图片。
  3. 使用Image.open()函数打开PNG图片,并使用.convert('RGB')将其转换为RGB模式。
  4. 使用list(image.getdata())获取图片的像素值列表。
  5. 创建一个字典pixels_to_extract,将指定的像素值映射到对应的数字代码。
  6. 遍历像素值列表,使用pixels_to_extract.get(pixel, 0)获取映射关系中的值,如果像素值不在映射关系中,则返回0。
  7. 使用f'{pixel[0]}, {pixel[1]}, {pixel[2]} '将转换后的像素值写入文本文件。
  8. 使用print()函数输出每个图片的像素数量统计结果。

使用方法:

  1. input_folderoutput_folder变量设置为你的输入文件夹和输出文件夹的路径。
  2. 运行代码。

注意:

  • 代码中使用的像素值映射关系pixels_to_extract需要根据你的实际需求进行修改。
  • 代码默认保存到.txt文本文件,你可以根据需要修改文件扩展名。

标签: 常规


原文地址: https://gggwd.com/t/topic/Uze 著作权归作者所有。请勿转载和采集!