from PIL import Image
import os
from collections import defaultdict

# 输入文件夹和输出文件夹的路径
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 = [(180, 0, 0), (232, 14, 14), (255, 208, 69), (79, 210, 125)]  # 严重拥堵,拥挤,缓行,畅通

# 统计每个像素值的个数
pixel_counts = defaultdict(int)

# 循环遍历输入文件夹中的所有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())
        
        # 将所有像素值保存到输出文件夹中的文本文件中
        output_path = os.path.join(output_folder, filename.replace('.png', '.txt'))
        with open(output_path, 'w') as file:
            for pixel in pixels:
                if pixel in pixels_to_extract:
                    file.write(f'{pixel[0]}, {pixel[1]}, {pixel[2]}
')
                    pixel_counts[pixel] += 1

# 将每种像素值的个数保存到输出文件夹中的统计文件中
statistic_path = os.path.join(output_folder, 'pixel_counts.txt')
with open(statistic_path, 'w') as file:
    for pixel, count in pixel_counts.items():
        file.write(f'{pixel[0]}, {pixel[1]}, {pixel[2]}: {count}
')

print('转换完成')

这段代码会遍历输入文件夹中的所有PNG图片,将每张图片的像素值保存到输出文件夹中的文本文件中,并统计指定像素值的数量。最后,将每种像素值的个数保存到输出文件夹中的统计文件中。注意,你需要将input_folderoutput_folder的路径修改为你自己的路径。

Python 图片像素值提取和统计:根据指定像素值提取并计数

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

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