In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Editor to share with you how to use K-Means clustering in Python+OpenCV for color quantification, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
Color quantization using K-Means clustering
The problem of color quantization can be defined as the process of reducing the number of colors in an image. Color quantization is very important for some devices to display images, and these devices may only display limited colors due to memory constraints. Therefore, color display on these devices usually requires a tradeoff between accuracy and reducing the number of colors. When using K-Means clustering for color quantization, the tradeoff between the two is carried out by correctly setting the K parameter.
K-Means clustering algorithm is used to perform color quantization. The cluster center data consists of three features, which correspond to the B, G and R values of each pixel of the image. Therefore, the key is to convert the image to data:
Data = np.float32 (image) .reshape (- 1,3)
To see how accuracy is weighed against the number of colors, we use different K values (3, 5, 10, 20, and 40) to perform the clustering process to see how the resulting image changes. If we want the resulting image with only 3 colors (K = 3), you need to do the following:
Load the BGR image:
Img = cv2.imread ('example.jpg')
Use the color_quantization () function to perform color quantization:
Def color_quantization (image, k): # convert the image to data data = np.float32 (image). Reshape ((- 1,3)) # algorithm termination condition criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20,1.0) # K-Means clustering ret, label, center = cv2.kmeans (data, k, None, criteria, 10 Cv2.KMEANS_RANDOM_CENTERS) # Cluster Center center = np.uint8 (center) # convert an image with k color center to uint8 result = center [label.flatten ()] result = result.reshape (img.shape) return resultcolor_3 = color_quantization (img, 3)
The key point in the color_quantization () function is the use of the cv2.kmeans () method. Finally, you can build an image with k colors and replace each pixel value with their corresponding center value. the result of the program is as follows:
Complete code
The complete code for color quantization using K-Means clustering is as follows:
Import numpy as npimport cv2from matplotlib import pyplot as pltdef show_img_with_matplotlib (color_img, title, pos): img_RGB = color_img [:,::-1] ax = plt.subplot (2,4, pos) plt.imshow (img_RGB) plt.title (title, fontsize=8) plt.axis ('off') def color_quantization (image, k): # convert the image to data data = np.float32 (image) .reshape ((- 1) 3)) # algorithm termination condition criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20,1.0) # K-Means clustering ret, label, center = cv2.kmeans (data, k, None, criteria, 10 Cv2.KMEANS_RANDOM_CENTERS) # Cluster Center center = np.uint8 (center) # convert an image with k color center to uint8 result = center [label.flatten ()] result = result.reshape (img.shape) return resultfig = plt.figure (figsize= (16,8)) plt.suptitle ("Color quantization using K-means clustering algorithm", fontsize=14 Fontweight='bold') # Image load img = cv2.imread ('example.png') show_img_with_matplotlib (img, "original image", 1) # Color quantization using different K values for i in range (7): color = color_quantization (img, (item1) * 10) show_img_with_matplotlib (color, "color quantization (k = {})" .format ((iTun1) * 10) ITun2) plt.show () displays the color distribution after color quantization
The above program can be extended to display the color distribution after color quantization, which shows the number of pixels assigned to each cluster center. Simply extend the color_quantization () function to include the required functionality:
Import collectionsdef color_quantization (image, k): # convert the image to data data = np.float32 (image). Reshape ((- 1,3)) # algorithm termination condition criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20,1.0) # K-Means clustering ret, label, center = cv2.kmeans (data, k, None, criteria, 10 Cv2.KMEANS_RANDOM_CENTERS) # Cluster center center = np.uint8 (center) # convert images with k color centers to uint8 result = center [label.flatten ()] result = result.reshape (img.shape) # count the number of pixels assigned to each cluster center counter = collections.Counter (label.flatten ()) print (counter) # calculate the total pixels of the input image Number total = img.shape [0] * img.shape [1] # specify the width and height for the color distribution image: desired_width = img.shape [1] desired_height = 70 desired_height_colors = 50 # initialize the color distribution image color_distribution = np.ones ((desired_height Desired_width, 3), dtype='uint8') * 255start = 0 for key, value in counter.items (): # Normalized value_normalized = value / total * desired_width end = start + value_normalized # draw a rectangle cv2.rectangle (color_distribution, (int (start), 0), (int (end), desired_height_colors), center.tolist () corresponding to the current color -1) start = end return np.vstack ((color_distribution, result))
In the above code, collections.Counter () is used to count the number of pixels assigned to each cluster center:
Counter = collections.Counter (label.flatten ())
For example, if K = 10, you can get the following results:
Counter ({7: 37199, 3: 36302, 0: 29299, 5: 23987, 6: 23895, 1: 20077, 9: 19814, 8: 18427,4: 16221,2: 14779})
After constructing the color distribution image, connect it with the color quantized image:
Np.vstack ((color_distribution, result))
The output of the program is as follows:
As can be seen from the above image, the larger the k value is, the more realistic the image is after changing the parameters k (10, 20, 30, 40, 50, 60 and 70) after applying color quantization using K-Means clustering algorithm.
Note: except for the color_quantization () function, because the other code has not been modified, it will not be given separately.
These are all the contents of this article entitled "how to use K-Means clustering for color quantization in Python+OpenCV". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.