python 列举图像颜色

1. 获取单张图片颜色

from PIL import Image
import numpy as np

# 因为 OpenCV 读取图片时,会修改部分图片模式
# 可以参考 https://blog.csdn.net/m0_49270962/article/details/124988735
# 所以选择 PIL 读取图片
img = Image.open(img_path)

color_list = np.unique(np.array(img).reshape(-1, len(img.getbands())), axis=0)
print(color_list)

2. 获取目录下所有图片颜色集合

2.1. 获取图片路径列表

import os
def get_img_path_list(img_dir):
    '''获取 img_dir 下所有图片的路径'''
    img_path_list = []
    for root, dirs, files in os.walk(img_dir):
        for file in files:
            img_path_list.append(osp.join(root, file))
    return img_path_list

2.2. 获取单张图片颜色集合

import numpy as np
from PIL import Image


def get_color_set(img_path) -> set:
    '''获取 img_path 图片的全部颜色

    Returns
    ---
    color_set: {(b, g, r), (b, g, r), ...}
    '''

    color_set = set()
    # 因为 OpenCV 读取图片时,会修改部分图片模式
    # 所以选择 PIL 读取图片
    img = Image.open(img_path)
    

    # color_list = np.unique(img.reshape(-1, img.shape[2]), axis=0)
    color_list = np.unique(np.array(img).reshape(-1, len(img.getbands())), axis=0)
    for color in color_list:
        color_set.add(tuple(color))
    return color_set

2.3. 获取图片颜色集合

def get_mul_color_set(img_dir):
    mul_color_set = set()
    img_path_list = get_img_path_list(img_dir)
    for img_path in img_path_list:
    	# 当图片多的时候可以print看一下进度
        # print(img_path)
        mul_color_set.update(get_color_set(img_path))
    return mul_color_set

2.4. 主函数

if __name__ == "__main__":
    print(get_mul_color_set(img_dir))

3. 附

这几日在处理语义分割的掩膜,但是

  1. 自己做的数据集不知道颜色配置的效果(归一化的图像常常一片黑)
  2. 引用的数据集不知道 label 的具体颜色值

所以就有了这篇拙作

4. 参考

python 3.x - Output the number of each RGB value of an mask image using pillow? - Stack Overflow: https://stackoverflow.com/questions/62842234/output-the-number-of-each-rgb-value-of-an-mask-image-using-pillow


  • 文章系个人学习总结,希望可以给大家带来些许启发,欢迎提出建议或给予指正。
  • 本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。
  • 欢迎大家转载分享,转载请标明源地址,谢谢

你可能感兴趣的:(Python,python,计算机视觉,图像处理)