【问题标题】:Matplotlib: How to plot images instead of points?Matplotlib:如何绘制图像而不是点?
【发布时间】:2014-04-29 06:20:56
【问题描述】:

我想将图像列表读入 Python/Matplotlib,然后在图表中绘制这些图像而不是其他标记(如点)。我尝试过使用 imshow 但没有成功,因为我无法将图像移动到另一个位置并适当地缩放它。也许有人有一个好主意:)

【问题讨论】:

标签: python image-processing matplotlib


【解决方案1】:

有两种方法可以做到这一点。

  1. 使用 imshowextent kwarg 绘制图像,该 kwarg 集基于您想要图像的位置。
  2. AnnotationBbox 中使用OffsetImage

第一种方式最容易理解,但第二种方式优势很大。注释框方法将允许图像在放大时保持恒定大小。使用imshow 会将图像的大小与绘图的数据坐标联系起来。

这是第二个选项的示例:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from matplotlib.cbook import get_sample_data

def main():
    x = np.linspace(0, 10, 20)
    y = np.cos(x)
    image_path = get_sample_data('ada.png')
    fig, ax = plt.subplots()
    imscatter(x, y, image_path, zoom=0.1, ax=ax)
    ax.plot(x, y)
    plt.show()

def imscatter(x, y, image, ax=None, zoom=1):
    if ax is None:
        ax = plt.gca()
    try:
        image = plt.imread(image)
    except TypeError:
        # Likely already an array...
        pass
    im = OffsetImage(image, zoom=zoom)
    x, y = np.atleast_1d(x, y)
    artists = []
    for x0, y0 in zip(x, y):
        ab = AnnotationBbox(im, (x0, y0), xycoords='data', frameon=False)
        artists.append(ax.add_artist(ab))
    ax.update_datalim(np.column_stack([x, y]))
    ax.autoscale()
    return artists

main()

【讨论】:

  • 那是艾达洛夫莱斯吗?太棒了。
  • 我试过你的方法,但对我不起作用。你认为你可以看看我的后续问题吗?在这里:stackoverflow.com/questions/48896088
  • 这很好,也只是指出缩放参数可以用来控制点的大小(指定为图像)
【解决方案2】:

如果您想要不同的图片:

这是谷歌搜索“matplotlib scatter with images”时的第一个回复。如果您像我一样,并且实际上需要在每张图像上绘制不同的图像,请尝试使用这个最小化的示例。请务必输入您自己的图片。

import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox

def getImage(path, zoom=1):
    return OffsetImage(plt.imread(path), zoom=zoom)

paths = [
    'a.jpg',
    'b.jpg',
    'c.jpg',
    'd.jpg',
    'e.jpg']
    
x = [0,1,2,3,4]
y = [0,1,2,3,4]

fig, ax = plt.subplots()
ax.scatter(x, y) 

for x0, y0, path in zip(x, y,paths):
    ab = AnnotationBbox(getImage(path), (x0, y0), frameon=False)
    ax.add_artist(ab)

【讨论】:

  • 我必须在循环的末尾ax.add_artist(ab)。是否有可能将其排除在示例之外?
  • @JoshuaR。你是对的。我有点过分热心地整理这个例子。确实应该添加ax.add_artist(ab)
  • @MitchellvanZuylen 如果我只想对所有点使用单个图像怎么办?谢谢
  • @pukumarathe 在当前版本中,我们为每个点传递不同的 path 值。如果您想要相同的图像,您可以每次为path 传递相同的值。或者,甚至更好地加载图像一次 im = OffsetImage(plt.imread(path)),然后将 for 循环中的 getImage(path) 替换为 im
  • OffsetImage 采用 zoom 参数。你可以玩弄它,这可以使图像更小(我认为甚至更大)
猜你喜欢
  • 2018-06-24
  • 2021-02-26
  • 2012-04-12
  • 2019-08-12
  • 2017-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多