python - 如何在这个 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()
解决方案
您必须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
这是我的标准测试图像的输出:
希望有帮助!
推荐阅读
- regex - 将多个文件从 Cloud Storage 导入 BigQuery 的命令
- reactjs - 如何在reactjs中的无序列表(ul)中创建自定义列表项(li)
- unit-testing - NUnit 没有运行通用的 TestFixture
- docker - Docker在RUN中使用环境变量
- python - 为什么我不能更改从 QWidget 派生的类的类变量?
- azure - 尽管已安装代理,但无法从 Azure DevOps(云 - PaaS)访问内部 SonarQube(本地)
- c++ - C++ 数组函数错误:下标值不是数组、指针或向量
- mikro-orm - Mikro-orm 错误:未发现实体“未定义”实体
- sql - Hive 表达式不在 GROUP BY 键 'pat_dtl_start_dt' 中(状态 = 42000,代码 = 10025)
- wso2 - 如何在 WSO2 API Manager 3.1.0 上添加 API?