【发布时间】:2011-06-19 03:02:15
【问题描述】:
我有一组 150x150 像素的 png 图像,以及它们对应的一组 (x, y) 坐标。有没有办法在网格上绘制图像?例如,我正在寻找 R 或 Python 解决方案来创建类似以下内容:
【问题讨论】:
标签: python r matplotlib plot
我有一组 150x150 像素的 png 图像,以及它们对应的一组 (x, y) 坐标。有没有办法在网格上绘制图像?例如,我正在寻找 R 或 Python 解决方案来创建类似以下内容:
【问题讨论】:
标签: python r matplotlib plot
您可以通过实例化 AnnotationBbox 来创建一个边界框——对每张图像执行一次 您希望展示的;图像及其坐标被传递给构造函数。
这两个图像的代码显然是重复的,所以一旦将该块放入一个函数中,它就不像这里看起来那么长。
import matplotlib.pyplot as PLT
from matplotlib.offsetbox import AnnotationBbox, OffsetImage
from matplotlib._png import read_png
fig = PLT.gcf()
fig.clf()
ax = PLT.subplot(111)
# add a first image
arr_hand = read_png('/path/to/this/image.png')
imagebox = OffsetImage(arr_hand, zoom=.1)
xy = [0.25, 0.45] # coordinates to position this image
ab = AnnotationBbox(imagebox, xy,
xybox=(30., -30.),
xycoords='data',
boxcoords="offset points")
ax.add_artist(ab)
# add second image
arr_vic = read_png('/path/to/this/image2.png')
imagebox = OffsetImage(arr_vic, zoom=.1)
xy = [.6, .3] # coordinates to position 2nd image
ab = AnnotationBbox(imagebox, xy,
xybox=(30, -30),
xycoords='data',
boxcoords="offset points")
ax.add_artist(ab)
# rest is just standard matplotlib boilerplate
ax.grid(True)
PLT.draw()
PLT.show()
【讨论】:
frameon=False 传递给AnnotationBbox()
在 R(2.11.0 及更高版本)中执行此操作的一种方法:
library("png")
# read a sample file (R logo)
img <- readPNG(system.file("img", "Rlogo.png", package="png"))
# img2 <- readPNG(system.file("img", "Rlogo.png", package="png"))
img2 <- readPNG("hand.png", TRUE) # here import a different image
if (exists("rasterImage")) {
plot(1:1000, type='n')
rasterImage(img, 100, 100, 200, 200)
rasterImage(img2, 300, 300, 400, 400)
}
请参阅 ?readPNG 和 ?rasterImage 了解详细信息。
【讨论】:
我会为此使用 matplotlib。 this demo 显示类似的东西,我相信它可以适应您的特定问题
【讨论】:
您还可以在 R 中使用 TeachingDemos 包中的 my.symbols 和 ms.image 函数。
【讨论】:
在 R 中,在 help(rasterImage) 中阅读:
require(grDevices)
#set up the plot region:
op <- par(bg = "thistle") <h>
plot(c(100, 250), c(300, 450), type = "n", xlab="", ylab="")
image <- as.raster(matrix(0:1, ncol=5, nrow=3))
rasterImage(image, 100, 300, 150, 350, interpolate=FALSE)
rasterImage(image, 100, 400, 150, 450)
rasterImage(image, 200, 300, 200 + xinch(.5), 300 + yinch(.3), interpolate=FALSE)
rasterImage(image, 200, 400, 250, 450, angle=15, interpolate=FALSE)
par(op)
....是一个很好的例子。
【讨论】: