如何使用matlib函数plt.imshow(image)显示多个图像?

时间:2020-04-22 17:48:03

标签: python matplotlib

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

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

2 个答案:

答案 0 :(得分:0)

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()

example plot

答案 1 :(得分:0)

直接的解决方案是改用plt.subplots:

import numpy as np
import matplotlib.pyplot as plt

lst_cmaps = ['Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
         'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
         'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn']

data = ((np.arange(100) % 10) * np.arange(100)).reshape(10, 10)

nxn = int(np.sqrt(len(lst_cmaps)))

plt, ax = plt.subplots(nxn, nxn)

for i, ax_ in enumerate(ax.flatten()):
    ax_.imshow(data, cmap=lst_cmaps[i])

这会给您这样的图像:

enter image description here