首页 > 解决方案 > 如何使用 matlib 函数 plt.imshow(image) 显示多个图像?

问题描述

def exiacc():
    global my_img, readimg , im, list_name, exis_img, tkimage
    print('Opening Existing Account...')
    topl = Toplevel()  
    readimg = './facedata/'
    list_img = os.listdir(readimg)
    row, col = 0, 0
    k = 0
    for fn in os.listdir(readimg):
        if fn.endswith('.jpg'):
            list_name.append(fn[:fn.index('_')])
            im = Image.open(os.path.join(readimg, fn))
            im2 = im.resize((200, 200), Image.LANCZOS)
            tkimage = ImageTk.PhotoImage(im2)
            exis_img = Label(topl, image=tkimage)
            exis_img.grid(row = row + 1, column = col + 1, padx=2, pady=2)
            exis_name = Label(topl, text = list_name[k] , font = ("consolas", 12, "bold"))
            exis_name.grid(row=row + 2, column = col + 1, padx=2, pady=2)
            col += 1
            k +=1
            if col == 5:
                row += 2
                col = 0

我的结果表明,只有最后处理的图像有效地覆盖了其他图像。

标签: pythonmatplotlib

解决方案


plt.imshow有一个参数extent=[x0, x1, y0, y1]可以将图像定位在绘图中的任何位置。令人讨厌的是,这imshow迫使纵横比“相等”(因此 x 和 y 中的距离被强制为相同数量的像素)。更烦人的是,imshow它还强行设置了 x 和 y 的限制。要拥有多个图像,需要明确设置限制(在调用之后imshow)。如果不需要“相等”的纵横比(图像通常需要它),set_aspect('auto')再次释放纵横比。

这是一个示例,使用不同的颜色图来获取不同颜色的图像。

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
cmaps = ['Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
         'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
         'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']
img = ((np.arange(100) % 10) * np.arange(100)).reshape(10, 10)
cols = 4
for i, cmap in enumerate(cmaps):
    plt.imshow(img, extent=[i % cols, i % cols +1, i // cols, i // cols +1], cmap=cmap)
plt.xlim(0, cols)
plt.ylim(0, (len(cmaps) - 1) // cols + 1)
plt.gca().set_aspect('auto') # allow a free aspect ratio, to fully fit the plot figure
plt.show()

示例图


推荐阅读