Find the main color composition of an image based on Python

AI algorithm and image processing 2020-11-16 17:24:47
main color composition image based


If we can know what the most colors in an image are , It can help us solve many practical problems . For example, in the field of agriculture, you want to determine the maturity of fruits , We can check whether the color of the fruit falls within a certain range , To see if they're mature .

Next we will use Python And some common libraries ( for example Numpy,Matplotlib and OpenCV) To solve this problem .

01. preparation

First step : Add package

We will load the basic package here . in addition , Because we are going to use Jupyter Programming , So don't forget to add %matplotlib inline command .

The second step : Load and display the sample image

We're going to show two images side by side , So we need to do an auxiliary function . Next, we'll load some of the sample images we'll use in this tutorial , And use the above functions to display it .

02. Common methods

Method 1 : Average

The first method is the simplest ( But it doesn't work ) Methods - Just find the average pixel value . Use numpy Of average function , We can easily get the average pixel values on rows and widths -axis=(0,1)

img_temp = img.copy()
img_temp[:,:,0], img_temp[:,:,1], img_temp[:,:,2] = np.average(img, axis=(0,1))
img_temp_2 = img_2.copy()
img_temp_2[:,:,0], img_temp_2[:,:,1], img_temp_2[:,:,2] = np.average(img_2, axis=(0,1))
show_img_compar(img, img_temp)
show_img_compar(img_2, img_temp_2)

From the above image, you can see , The average method can produce incorrect results , The most common color it gives may not be the color we want , This is because the average takes into account all pixel values . When we have high contrast images ( An image contains “ light colour ” and “ Dark ”) This problem will be serious at the time . In the second picture , This is more clear . It gives us a new color , The color is not visible in the image at all .

Method 2 : Highest pixel frequency

The second method will be more accurate than the first . Our job is to calculate the number of times each pixel value appears .numpy It provides us with a function to complete this task . But first of all , We have to adjust the shape of the image data structure , To provide only 3 List of values ( Every R,G and B Channel strength one ).

We can use numpy Of reshape Function to get a list of pixel values .

Now we have the right structure of data , You can start calculating the frequency of pixel values , Use numpy Medium unique Function .

img_temp = img.copy()
unique, counts = np.unique(img_temp.reshape(-1, 3), axis=0, return_counts=True)
img_temp[:,:,0], img_temp[:,:,1], img_temp[:,:,2] = unique[np.argmax(counts)]
img_temp_2 = img_2.copy()
unique, counts = np.unique(img_temp_2.reshape(-1, 3), axis=0, return_counts=True)
img_temp_2[:,:,0], img_temp_2[:,:,1], img_temp_2[:,:,2] = unique[np.argmax(counts)]
show_img_compar(img, img_temp)
show_img_compar(img_2, img_temp_2)

Is it more meaningful than the first one ? The most common color is the black area . But if we don't just use one of the most common colors , What do you do with more colors ? Use the same concept , We can use N The most common color . let me put it another way , What do we do with the most common color clusters .

Method 3 : Use K Mean clustering

We can use famous K Mean clustering clusters color groups together .

def palette(clusters):
width=300
palette = np.zeros((50, width, 3), np.uint8)
steps = width/clusters.cluster_centers_.shape[0]
for idx, centers in enumerate(clusters.cluster_centers_):
palette[:, int(idx*steps):(int((idx+1)*steps)), :] = centers
return palette
clt_1 = clt.fit(img.reshape(-1, 3))
show_img_compar(img, palette(clt_1))
clt_2 = clt.fit(img_2.reshape(-1, 3))
show_img_compar(img_2, palette(clt_2))

Easy ! Now? , What we need is a function that displays the color clusters above and displays them immediately . We just need to create a height of 50, Width is 300 Pixel images to display color groups / palette . For each color cluster , We assign it to our palette .

Isn't it beautiful ? In terms of the most common colors in an image ,K The mean clustering gives excellent results . In the second image , We can see too many shades of brown in the palette . It's probably because we've chosen too many clusters . Let's see if we can choose the smaller k Value to fix it .

def palette(clusters):
width=300
palette = np.zeros((50, width, 3), np.uint8)
steps = width/clusters.cluster_centers_.shape[0]
for idx, centers in enumerate(clusters.cluster_centers_):
palette[:, int(idx*steps):(int((idx+1)*steps)), :] = centers
return palette
clt_3 = KMeans(n_clusters=3)
clt_3.fit(img_2.reshape(-1, 3))
show_img_compar(img_2, palette(clt_3))

Because we use K Mean clustering , So we still have to determine the appropriate number of clusters ourselves . Three clusters seem to be a good choice . But we can still improve these results , And still can solve the cluster problem . How do we also show the percentage of clusters in the whole image ?

Method four :K mean value + The scale shows

What we need to do is modify our palette function . Instead of using fixed steps , We change the width of each cluster to be proportional to the number of pixels in that cluster .

from collections import Counter
def palette_perc(k_cluster):
width = 300
palette = np.zeros((50, width, 3), np.uint8)
n_pixels = len(k_cluster.labels_)
counter = Counter(k_cluster.labels_) # count how many pixels per cluster
perc = {}
for i in counter:
perc[i] = np.round(counter[i]/n_pixels, 2)
perc = dict(sorted(perc.items()))
#for logging purposes
print(perc)
print(k_cluster.cluster_centers_)
step = 0
for idx, centers in enumerate(k_cluster.cluster_centers_):
palette[:, step:int(step + perc[idx]*width+1), :] = centers
step += int(perc[idx]*width+1)
return palette
clt_1 = clt.fit(img.reshape(-1, 3))
show_img_compar(img, palette_perc(clt_1))
clt_2 = clt.fit(img_2.reshape(-1, 3))
show_img_compar(img_2, palette_perc(clt_2))

It not only provides us with the most common colors in images . It also gives us the proportion of each pixel that appears .

03. Conclusion

We introduced several uses Python And the best-known library to capture the most common colors in images . in addition , We also see the advantages and disadvantages of these technologies . up to now , Use k> 1 Of K Mean finding the most common colors is one of the best solutions to finding the most frequent colors in an image .

Code link :https://github.com/mrakelinggar/data-stuffs/tree/master/frequent_color

This article is from WeChat official account. - AI Algorithm and image processing (AI_study) , author : Nuby

The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the yunjia_community@tencent.com Delete .

Original publication time : 2020-11-09

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[AI algorithm and image processing]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database