如何在matplotlib中获得像素颜色? [英] How can I get the pixel colors in matplotlib?

查看:291
本文介绍了如何在matplotlib中获得像素颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用matplotlib.patches绘制矩形的集合.我的代码是:

I am plotting a collection of rectangles with matplotlib.patches. My code is:

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.不幸的是,我在互联网上找不到任何解决方案.

The rectangles may be overlapping, therefore some of them may be completely hidden. Do you know if it is possible to get the colors of the visible rectangles? I mean the colors of the rectangles that are not completely hidden and therefore that can be actually viewed by the user. I was thinking to some function that returns the color of the pixels, but more intelligent ideas are welcome. If possible, I'd prefer to not use PIL. Unfortunately I cannot find any solution on the internet.

推荐答案

跟随Vlass Sokolov的评论以及此 Stackoverflow帖子,作者: Joe Kington,这是您如何获得一个numpy数组,其中包含在matplotlib图形上可见的所有唯一颜色:

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

这篇关于如何在matplotlib中获得像素颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆