opencv计算图片中出现面积最大最经常出现的颜色
- opencv
- K均值聚类算法
- 颜色相似性,欧几里得距离越小,颜色越相似
| import math |
| import cv2 |
| import numpy as np |
| from sklearn.cluster import KMeans |
| |
| def find_dominant_color(image, k=2): |
| |
| image = image.reshape((image.shape[0] * image.shape[1], 3)) |
| |
| kmeans = KMeans(n_clusters=k,n_init=10) |
| kmeans.fit(image) |
| |
| counts = np.bincount(kmeans.labels_) |
| |
| return kmeans.cluster_centers_[np.argmax(counts)] |
| |
| |
| |
| def compute_color_similarity(color1,color2): |
| distance = math.sqrt(sum((c1-c2)**2 for c1, c2 in zip(color1, color2))) |
| return distance |
| |
| |
| def show_most_common_color(dominant_color): |
| |
| image = np.zeros((300, 300, 3), np.uint8) |
| image[:] = dominant_color |
| |
| cv2.imshow('Image', image) |
| cv2.waitKey(0) |
| |
| if __name__ == '__main__': |
| |
| image = cv2.imread('test1.jpg') |
| |
| dominant_color = find_dominant_color(image) |
| |
| show_most_common_color(dominant_color) |
| |
| |
| common_color = dominant_color[::-1] |
| print("Dominant color rgb:",common_color ) |
| |
| |
| |
| base_color = [69, 123, 209] |
| similarity = compute_color_similarity(common_color,base_color) |
| print("similarity = :",similarity) |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战