Matplotlib:绘制图像而不是点来绘制图像

时间:2018-02-20 23:51:11

标签: python matplotlib image-processing

对我来说有用的是将我的矩阵规范化为0到1而不是0到255.我不知道为什么会这样,但如果有人有解释,我会接受答案。

原始问题

我有一个白色字段上的黑色矩形图像数据集。例如,这里有三个这样的图像(对不起,没有边框):

enter image description here enter image description here enter image description here

我想构建一个散点图,其中每个数据点都表示为一个图像。我使用了this SO中的代码,但得到了一个看起来像这样的图(用边框绘制调试):

enter image description here

如您所见,图像看起来都像正方形。实际上,它们应该是各种尺寸的矩形,在框架内具有不同的位置。有办法解决这个问题吗?

这是一些生成一些图像的代码,然后将它们绘制为散点图。您可以看到它保存的图像(您需要在运行脚本的同一目录中创建images目录)与matplotlib绘制的图像不同:

from PIL import Image
import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import matplotlib.patches as patches
import random
import numpy as np

# ------------------------------------------------------------------------------

def create_image():
    rx = random.random()
    ry = random.random()
    rw = random.random() / 2
    rh = random.random() / 2
    DPI = 72
    fig = plt.figure(frameon=False,
                     figsize=(32/DPI, 32/DPI),
                     dpi=DPI)
    ax = fig.add_axes([0, 0, 1, 1])
    ax.axis('off')
    rect = patches.Rectangle((rx, ry),
                             rw, rh,
                             linewidth=1,
                             edgecolor='none',
                             facecolor=(0, 0, 0))
    ax.add_patch(rect)
    fig.canvas.draw()
    img = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8)
    width, height = fig.get_size_inches() * fig.get_dpi()
    img = img.reshape((32, 32, 3))
    img = img.T
    fig.savefig('images/%s.png' % i)
    plt.clf()
    plt.close()
    return img

# ------------------------------------------------------------------------------

def imscatter(points, images, ax):
    for (x, y), image in zip(points, images):
        im = OffsetImage(image.T, zoom=1)
        ab = AnnotationBbox(im, (x, y), frameon=True, pad=0.2)
        ax.add_artist(ab)

# ------------------------------------------------------------------------------

fig, ax = plt.subplots()

# Create ten random points.
N_SAMPLES = 10
points = np.random.random((N_SAMPLES,2)) * 100
images = np.zeros((N_SAMPLES, 3, 32, 32))
for i in range(N_SAMPLES):
    images[i] = create_image()

Xp = points[:, 0]
Yp = points[:, 1]

ax.set_xlim([Xp.min().astype(int), Xp.max().astype(int)])
ax.set_ylim([Yp.min().astype(int), Yp.max().astype(int)])

imscatter(points, images, ax)

plt.show()

来自评论:

@ImportanceOfBeingErnest在本地运行我的脚本时得到this image,而我得到this image。我的猜测是,这与DPI或分辨率有某种关系。

0 个答案:

没有答案