How can I get the pixel colors in matplotlib?

≡放荡痞女 提交于 2019-12-04 17:13:53
Jean-Sébastien

Following Vlass Sokolov comment and this Stackoverflow post by Joe Kington, here is how you could get a numpy array containing all the unique colors that are visible on a matplotlib figure:

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()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!