python 获取图像色彩丰富度

📅 2026/7/10 1:01:46
python 获取图像色彩丰富度
import glob import os import cv2 import numpy as np def color_richness_by_hue_histogram(image, resizeTrue): 基于色相直方图的色彩丰富度评估 完全不受明度影响 if isinstance(image, str): img cv2.imread(image) else: img image.copy() if img is None: return 0 if resize and img.shape[0] 300: img cv2.resize(img, (300, 300)) hsv cv2.cvtColor(img, cv2.COLOR_BGR2HSV) H, S, V cv2.split(hsv) # 去除低饱和度像素灰色 mask S 15 H_valid H[mask] if len(H_valid) 100: return 0 # 核心统计色相直方图 hist, _ np.histogram(H_valid, bins36, range(0, 180)) # 1. 覆盖率有多少色相bin被占用 occupied_bins np.sum(hist 0) coverage occupied_bins / 36 # 2. 分布均匀度熵 hist_normalized hist / np.sum(hist) hist_normalized hist_normalized[hist_normalized 0] # 去掉0值 entropy -np.sum(hist_normalized * np.log2(hist_normalized)) max_entropy np.log2(36) uniformity entropy / max_entropy # 3. 主色占比越集中分数越低 dominant_ratio np.max(hist) / np.sum(hist) dominance_penalty 1 - dominant_ratio # 0-1之间越高越分散 # 综合评分 # 覆盖率 均匀度 分散度 score coverage * 0.4 uniformity * 0.4 dominance_penalty * 0.2 score score * 100 return min(100, score) import glob import os import cv2 import numpy as np def color_richness_robust(image, resizeTrue): 鲁棒的色彩丰富度评估 结合多种方法消除亮度干扰 if isinstance(image, str): img cv2.imread(image) else: img image.copy() if img is None: return 0 if resize and img.shape[0] 300: img cv2.resize(img, (300, 300)) hsv cv2.cvtColor(img, cv2.COLOR_BGR2HSV) H, S, V cv2.split(hsv) # 过滤低饱和度像素排除灰色 mask S 15 H_valid H[mask] S_valid S[mask] if len(H_valid) 100: return 0 # 指标1色相覆盖率 hist, _ np.histogram(H_valid, bins36, range(0, 180)) coverage np.sum(hist 0) / 36 # 指标2色相分散度使用百分位距 # 使用IQR四分位距替代标准差更鲁棒 q75, q25 np.percentile(H_valid, [75, 25]) iqr q75 - q25 spread min(1.0, iqr / 90) # 归一化 # 指标3饱和度修正 # 使用中位数不受极端值影响 s_median np.median(S_valid) sat_score min(1.0, s_median / 200) # 指标4均匀度 hist_norm hist[hist 0] / np.sum(hist[hist 0]) entropy -np.sum(hist_norm * np.log2(hist_norm 1e-10)) max_entropy np.log2(36) uniformity entropy / max_entropy # 综合评分 score coverage * 0.30 spread * 0.30 uniformity * 0.25 sat_score * 0.15 score score * 100 return min(100, score) if __name__ __main__: dir_arC:\Users\ChanJing-01\Pictures\haitun dir_arC:\Users\ChanJing-01\Pictures\niu filesglob.glob(os.path.join(dir_a,*.png)) for image_path in files: score color_richness_robust(image_path) print(score,image_path)