Share an interesting Python visualization technique

As shown below:

There are various colors in the sample photos. We will use Python to The visualization module and the opencv module identify all the color elements in the picture and add them to the color matching of the visual chart.
Import the module and load the picture
As usual, the first step is to import the module. The module used for visualization is the matplotlib module. We extract the colors from the picture and save them. In the color map table, so to use the colormap module, it also needs to be imported.
import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.patches as patches import matplotlib.image as mpimg from PIL import Image from matplotlib.offsetbox import OffsetImage, AnnotationBbox import cv2 import extcolors from colormap import rgb2hex
Then let’s load the image first. The code is as follows:
input_name = 'test_1.png'
img = plt.imread(input_name)
plt.imshow(img)
plt.axis('off')
plt.show()
output
Extract the colors and integrate them into a table
What we call is The extcolors module extracts colors from images. The output result is the color presented in RGB form. The code is as follows:
colors_x = extcolors.extract_from_path(img_url, tolerance=12, limit = 12) colors_x
output
([((3, 107, 144), 180316), ((17, 129, 140), 139930), ((89, 126, 118), 134080), ((125, 148, 154), 20636), ((63, 112, 126), 18728), ((207, 220, 226), 11037), ((255, 255, 255), 7496), ((28, 80, 117), 4972), ((166, 191, 198), 4327), ((60, 150, 140), 4197), ((90, 94, 59), 3313), ((56, 66, 39), 1669)], 538200)
We integrate the above results into a DataFrame data set, The code is as follows:
def color_to_df(input_color):
colors_pre_list = str(input_color).replace('([(', '').split(', (')[0:-1]
df_rgb = [i.split('), ')[0] + ')' for i in colors_pre_list]
df_percent = [i.split('), ')[1].replace(')', '') for i in colors_pre_list]
# 将RGB转换成十六进制的颜色
df_color_up = [rgb2hex(int(i.split(", ")[0].replace("(", "")),
int(i.split(", ")[1]),
int(i.split(", ")[2].replace(")", ""))) for i in df_rgb]
df = pd.DataFrame(zip(df_color_up, df_percent), columns=['c_code', 'occurence'])
return dfWe try to call our custom function above and output the result to the DataFrame data set.
df_color = color_to_df(colors_x) df_color
output

Drawing the chart
The next step is to draw the chart. The matplotlib module is used. The code is as follows :
fig, ax = plt.subplots(figsize=(90,90),dpi=10)
wedges, text = ax.pie(list_precent,
labels= text_c,
labeldistance= 1.05,
colors = list_color,
textprops={'fontsize': 120, 'color':'black'}
)
plt.setp(wedges, width=0.3)
ax.set_aspect("equal")
fig.set_facecolor('white')
plt.show()output

The pie chart shows the proportion of each different color. We further place the original image in the ring. among.
imagebox = OffsetImage(img, zoom=2.3) ab = AnnotationBbox(imagebox, (0, 0)) ax1.add_artist(ab)
output

Finally make a color palette to list all the different colors in the original image. The code is as follows:
## 调色盘
x_posi, y_posi, y_posi2 = 160, -170, -170
for c in list_color:
if list_color.index(c) <= 5:
y_posi += 180
rect = patches.Rectangle((x_posi, y_posi), 360, 160, facecolor = c)
ax2.add_patch(rect)
ax2.text(x = x_posi+400, y = y_posi+100, s = c, fontdict={'fontsize': 190})
else:
y_posi2 += 180
rect = patches.Rectangle((x_posi + 1000, y_posi2), 360, 160, facecolor = c)
ax2.add_artist(rect)
ax2.text(x = x_posi+1400, y = y_posi2+100, s = c, fontdict={'fontsize': 190})
ax2.axis('off')
fig.set_facecolor('white')
plt.imshow(bg)
plt.tight_layout()output

Practical link
This is the actual link. We encapsulate all the above codes into a complete function.
def exact_color(input_image, resize, tolerance, zoom):
output_width = resize
img = Image.open(input_image)
if img.size[0] >= resize:
wpercent = (output_width/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((output_width,hsize), Image.ANTIALIAS)
resize_name = 'resize_'+ input_image
img.save(resize_name)
else:
resize_name = input_image
fig.set_facecolor('white')
ax2.axis('off')
bg = plt.imread('bg.png')
plt.imshow(bg)
plt.tight_layout()
return plt.show()
exact_color('test_2.png', 900, 12, 2.5)output

The above is the detailed content of Share an interesting Python visualization technique. For more information, please follow other related articles on the PHP Chinese website!
Python: Automation, Scripting, and Task ManagementApr 16, 2025 am 12:14 AMPython excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.
Python and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AMTo maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.
Python: Games, GUIs, and MoreApr 13, 2025 am 12:14 AMPython excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.
Python vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AMPython is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.
The 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AMYou can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.
Python: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AMPython is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.
How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PMYou can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.
How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AMHow to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.







