首页 > 解决方案 > 如何在这个 for 循环中使用 subplot 在单个图中显示多张图片?

问题描述

这是我的代码。我想使用 Matplotlib 显示多个图像subplot。该代码是将图像拆分为 4 个部分。然后我想显示图像部分,但是这段代码一个接一个地显示它们。

import cv2
from matplotlib import pyplot as plt

im = cv2.imread("D:\\joker.jpg")
imgheight=im.shape[0]
imgwidth=im.shape[1]

y1 = 0
M = imgheight//2
N = imgwidth//2

for y in range(0,imgheight,M):
    for x in range(0, imgwidth, N):
        y1 = y + M
        x1 = x + N
        tiles = im[y:y+M,x:x+N]

        # cv2.rectangle(im, (x, y), (x1, y1), (0, 255, 0))
        gg =cv2.cvtColor(tiles, cv2.COLOR_BGR2RGB)
        # cv2.imwrite("save" + str(x) + '_' + str(y)+".png",tiles)

        plt.imshow(gg)
        plt.xticks([]), plt.yticks([])
        plt.show()

标签: pythonopencvmatplotlib

解决方案


您必须subplot在显示每个图像之前实际使用该命令。plt.show()此外,将嵌套循环移到外部可能是有益的。

这是我对您的修改代码的解决方案:

k = 0                                                   # Initialize subplot counter
for y in range(0,imgheight,M):
    for x in range(0, imgwidth, N):
        k += 1
        y1 = y + M
        x1 = x + N
        tiles = im[y:y+M,x:x+N]
        gg =cv2.cvtColor(tiles, cv2.COLOR_BGR2RGB)
        plt.subplot(2, 2, k)                            # Address proper subplot in 2x2 array
        plt.imshow(gg)
        plt.xticks([]), plt.yticks([])
plt.show()                                              # Moved plt.show() outside the loop

这是我的标准测试图像的输出:

输出

希望有帮助!


推荐阅读