我面临的问题是让matplotlib图形从之前运行的一个python脚本中显示出来.我的意思是,脚本不再运行,但我仍然可以"随机"地显示这个数字.可能是每次我运行不同的python脚本来保存matplotlib图形,但不完全确定.

详细信息:

  • 这些脚本是从vscode集成终端执行的.
  • 当图形出现时,我可以在我的GPU上看到进程,或者使用top命令,但我一关闭图形窗口,进程就消失了,稍后会重新出现.

代码片段:

from pytorch_grad_cam import GradCAM
from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
from pytorch_grad_cam.utils.image import show_cam_on_image
from torchvision.models import resnet50
import torch
import matplotlib.pyplot as plt

model = resnet50(pretrained=True)
target_layers = [model.layer4[-1]]
# load an image an put it in a pytorch tensor
input_tensor = torch.rand(1, 3, 224, 224)
# Create an input tensor image for your model..
# Note: input_tensor can be a batch tensor with several images!

# Construct the CAM object once, and then re-use it on many images:
cam = GradCAM(model=model, target_layers=target_layers, use_cuda=True)

targets = [ClassifierOutputTarget(281)]

# You can also pass aug_smooth=True and eigen_smooth=True, to apply smoothing.
grayscale_cam = cam(input_tensor=input_tensor, targets=targets)

# In this example grayscale_cam has only one image in the batch:
grayscale_cam = grayscale_cam[0, :]
rgb_img = input_tensor[0, :].permute(1, 2, 0).cpu().numpy()
visualisation = show_cam_on_image(rgb_img, grayscale_cam, use_rgb=True)

plt.figure()
plt.imshow(visualisation)
plt.show()
plt.close('all')

操作系统:Ubuntu 20.04 巨 Python :3.9.16

到目前为止,我try 了以下几点:

  • 当它出现时终止进程
  • 正在重新启动PC
  • 在我的虚拟环境中卸载并重新安装matplotlib
  • 查看父进程使用pstree并终止它.
  • 我们正在运行脚本并添加plt.clf().

这可能与试图在有问题的脚本中使用plt.ion()有关.或者从here开始在pytorch_grad_cam包的后台使用的OpenCV库.

Update:. - It seems that what triggers the figures is saving a file in my vscode editor....

  • 在pstree提示中,链接到matplotlib图的python进程有一个代码(即vscode)父进程

推荐答案

我的脚本被触发是因为文件名以test_*开头,并且加载的python环境包含了pytest包.我不知道在启用了VS代码Python扩展时,通过保存修改后的文件来触发pytest.

Python相关问答推荐

Pandas或pyspark跨越列创建

Pandas数据帧处理Pandas表中Json内的嵌套列表以获取后续Numpy数组

根据多列和一些条件创建新列

使用regex分析具有特定字符的字符串(如果它们存在)

剧作家Python没有得到回应

如何处理嵌套的SON?

使用polars .滤镜进行切片速度比pandas .loc慢

如何让 turtle 通过点击和拖动来绘制?

将DF中的名称与另一DF拆分并匹配并返回匹配的公司

滚动和,句号来自Pandas列

切片包括面具的第一个实例在内的眼镜的最佳方法是什么?

如何在solve()之后获得症状上的等式的值

Django REST Framework:无法正确地将值注释到多对多模型,不断得到错误字段名称字段对模型无效'<><>

形状弃用警告与组合多边形和多边形如何解决

Plotly Dash Creating Interactive Graph下拉列表

解决调用嵌入式函数的XSLT中表达式的语法移位/归约冲突

在pandas数据框中计算相对体积比指标,并添加指标值作为新列

使用BeautifulSoup抓取所有链接

如何找出Pandas 图中的连续空值(NaN)?

具有相同图例 colored颜色 和标签的堆叠子图