使用Python,OpenCV計算跑圖的圖像彩色度
這篇博客將介紹如何計算跑圖里最鮮艷的top25圖片和最灰暗的top25圖片并顯示色彩彩色度值展示。
效果圖
以下分別是最鮮艷top25和最灰暗top25對比效果圖:
最鮮艷top25效果圖:
最灰暗top25效果圖如下:
源碼見如下鏈接
https://blog.csdn.net/qq_40985985/article/details/115014533
# USAGE
# python colorfulness.py --images E:\personal\images# 導入必要的包
from imutils import build_montages
from imutils import paths
import numpy as np
import argparse
import imutils
import cv2# 圖像彩色度計算方法
def image_colorfulness(image):# 分離照片為三通道RGB值(B, G, R) = cv2.split(image.astype("float"))# 計算 rg = R - G 紅綠對手顏色空間rg = np.absolute(R - G)# 計算 yb = 0.5 * (R + G) - B 黃藍對手顏色空間yb = np.absolute(0.5 * (R + G) - B)# 計算`rg` and `yb` 的標準方差和均值(rgMean, rgStd) = (np.mean(rg), np.std(rg))(ybMean, ybStd) = (np.mean(yb), np.std(yb))# 將標準方差和均值合并stdRoot = np.sqrt((rgStd ** 2) + (ybStd ** 2))meanRoot = np.sqrt((rgMean ** 2) + (ybMean ** 2))# 獲得圖像彩色度量值,并返回return stdRoot + (0.3 * meanRoot)# 構建命令行參數,并解析
# --image 輸入圖片文件夾路徑
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--images", required=False,default='bm_sports/sports/',help="path to input directory of images")
args = vars(ap.parse_args())# 初始化結果list
print("[INFO] computing colorfulness metric for dataset...")
# 通常情況下存儲圖像id:圖像炫彩度量值,在這里介于圖像數據量小且為了后續展示方便,存儲圖像:圖像炫彩度量值
results = []# 遍歷圖片路徑
for imagePath in paths.list_images(args["images"]):# 加載圖像,保持寬高比的縮放以加快處理速度,計算圖像彩色度度量image = cv2.imread(imagePath)image = imutils.resize(image, width=250)C = image_colorfulness(image)# 顯示圖像的彩色度分數cv2.putText(image, "{:.2f}".format(C), (40, 40),cv2.FONT_HERSHEY_SIMPLEX, 1.4, (0, 255, 0), 3)# 添加圖像的炫彩度量到結果listresults.append((image, C))# 對結果進行排序最炫彩圖像靠前;
# 選出最炫彩、最不炫彩的25個圖像
print("[INFO] displaying results...")
results = sorted(results, key=lambda x: x[1], reverse=True)
mostColor = [r[0] for r in results[:25]]
leastColor = [r[0] for r in results[-25:]][::-1]# 構建倆組圖像的蒙太奇效果
mostColorMontage = build_montages(mostColor, (128, 128), (5, 5))
leastColorMontage = build_montages(leastColor, (128, 128), (5, 5))# 顯示圖像結果
cv2.imshow("Most Colorful", mostColorMontage[0])
cv2.imshow("Least Colorful", leastColorMontage[0])
cv2.waitKey(0)
cv2.destroyAllWindows()