我以以下方式在循环中绘制图像:
plt.figure(figsize=(20, 35))
for i in range(len(batchX)): # 32 images
plt.subplot(8, 4, 1 + i)
plt.title("IMG{} - Pred: {}, GT: {}".format(i+1, classes[int(pred[i][0])], classes[int(batchy[i])]))
plt.imshow(batchX[i])
plt.tight_layout()
plt.show()
我想根据某个条件改变每个情节的背景颜色(正如你可能已经猜到的,当预测等于地面真相时)。
我尝试在imshow()
之前的循环中添加这个:
if classes[int(pred[i][0])] == classes[int(batchy[i])]:
plt.gcf().set_facecolor("green")
else:
plt.gcf().set_facecolor("red")
但是,只有最后一个plt。gcf()
调用将被考虑,因为它是在plt时进行的。show()
运行时,它将查看颜色设置,使所有背景为绿色或红色。
我还能通过什么其他方式实现这一目标?
您可以使用subplot()并在轴上迭代,以最终显示具有正确背景颜色的所有绘图。
fig, axs = plt.subplots(8,4, figsize=(20, 35))
# Flattens the Axes grid to more easily iterate
axs = axs.flatten()
# You must make sure that len(axes) >= len(batchX) (and batchy)
for i, X in enumerate(batchX):
ax = axs[i]
ax.set_title("IMG{} - Pred: {}, GT: {}".format(i+1, classes[int(pred[i][0])],\
classes[int(batchy[i])]))
if classes[int(pred[i][0])] == classes[int(batchy[i])]:
ax.set_facecolor("green")
else:
ax.set_facecolor("red")
ax.imshow(X)
plt.tight_layout()
plt.show()