【发布时间】:2014-04-29 06:20:56
【问题描述】:
我想将图像列表读入 Python/Matplotlib,然后在图表中绘制这些图像而不是其他标记(如点)。我尝试过使用 imshow 但没有成功,因为我无法将图像移动到另一个位置并适当地缩放它。也许有人有一个好主意:)
【问题讨论】:
标签: python image-processing matplotlib
我想将图像列表读入 Python/Matplotlib,然后在图表中绘制这些图像而不是其他标记(如点)。我尝试过使用 imshow 但没有成功,因为我无法将图像移动到另一个位置并适当地缩放它。也许有人有一个好主意:)
【问题讨论】:
标签: python image-processing matplotlib
有两种方法可以做到这一点。
imshow 和 extent kwarg 绘制图像,该 kwarg 集基于您想要图像的位置。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()
【讨论】:
如果您想要不同的图片:
这是谷歌搜索“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)。是否有可能将其排除在示例之外?
ax.add_artist(ab)。
path 值。如果您想要相同的图像,您可以每次为path 传递相同的值。或者,甚至更好地加载图像一次 im = OffsetImage(plt.imread(path)),然后将 for 循环中的 getImage(path) 替换为 im
OffsetImage 采用 zoom 参数。你可以玩弄它,这可以使图像更小(我认为甚至更大)