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

2024-06-30 16:34:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


Tags: nameimageimgifoscollistrow
2条回答

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

一个直接的解决方案是使用plt.subplot代替:

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

相关问题 更多 >