Skip to main content
 首页 » 编程设计

python之如何获得 matplotlib 中的像素颜色

2024年10月17日8findumars

我正在使用 matplotlib.patches 绘制一组矩形。我的代码是:

import matplotlib.pyplot as plt 
import matplotlib.patches as patches 
 
fig = plt.figure(figsize=(14, 10)) 
 
for i in rectangles_list: 
 
    ax1 = fig.add_subplot(111, aspect='equal') 
    ax1.add_patch(patches.Rectangle( 
                 (x[i], y[i]), 
                  width[i], 
                  height[i], 
                  alpha = 1.0, 
                  facecolor = colors_list[i] 
                 ) 
                 ) 
 
plt.show() 

矩形可能重叠,因此其中一些可能被完全隐藏。你知道是否可以获得可见矩形的颜色吗?我的意思是矩形的颜色没有完全隐藏,因此用户可以实际查看。我在考虑一些返回像素颜色的函数,但欢迎更聪明的想法。如果可能的话,我宁愿不使用 PIL。不幸的是,我无法在互联网上找到任何解决方案。

请您参考如下方法:

继 Vlass Sokolov 评论和此 Stackoverflow post由 Joe Kington 撰写,这里是你如何获得一个包含所有在 matplotlib 图形上可见的独特颜色的 numpy 数组:

import matplotlib.pyplot as plt 
from matplotlib.patches import Rectangle 
import numpy as np 
 
plt.close('all') 
 
# Generate some data : 
 
N = 1000 
x, y = np.random.rand(N), np.random.rand(N) 
w, h = np.random.rand(N)/10 + 0.05, np.random.rand(N)/10 + 0.05 
colors = np.vstack([np.random.random_integers(0, 255, N), 
                    np.random.random_integers(0, 255, N), 
                    np.random.random_integers(0, 255, N)]).T 
 
# Plot and draw the data : 
 
fig = plt.figure(figsize=(7, 7), facecolor='white') 
ax = fig.add_subplot(111, aspect='equal') 
for i in range(N): 
    ax.add_patch(Rectangle((x[i], y[i]), w[i], h[i], fc=colors[i]/255., ec='none')) 
ax.axis([0, 1, 0, 1]) 
ax.axis('off') 
fig.canvas.draw() 
 
# Save data in a rgb string and convert to numpy array : 
 
rgb_data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') 
rgb_data = rgb_data.reshape((int(len(rgb_data)/3), 3)) 
 
# Keep only unique colors : 
 
rgb_data = np.vstack({tuple(row) for row in rgb_data}) 
 
# Show and save figure : 
 
fig.savefig('rectangle_colors.png') 
plt.show()