1. 获取单张图片颜色
from PIL import Image
import numpy as np
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()
img = Image.open(img_path)
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:
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. 附
这几日在处理语义分割的掩膜,但是
- 自己做的数据集不知道颜色配置的效果(归一化的图像常常一片黑)
- 引用的数据集不知道 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
|