错误“ _GeneratorContextManager”对象不可下标

时间:2019-12-18 00:55:55

标签: python memory deep-learning devops contextmanager

我遇到了“错误'_GeneratorContextManager'对象无法下标”错误

在生成图像的新功能时尝试使用contextmanager
这会占用太多内存,因此我想在函数完成调用后释放内存

@contextmanager
    def generate_image(self, img, i):
        #print("=================generate image=============================")
        img = Variable(img, requires_grad=True)

        #image_PIL = transforms.ToPILImage()(img[0])
        #image_PIL.save('result/test{}.jpg'.format(i))

        self.net._modules.get(self.finalconv_name).register_forward_hook(self.hook_feature)

        img_tensor = img.to(self.device)
        logit , _ = self.net(img_tensor)
        h_x = F.softmax(logit, dim=1).data.squeeze()

        weight_softmaxtemp = self.weight_softmax
        feature_blobstemp = self.feature_blobs[0]
        probs, idx = h_x.sort(0, True)
        idx_temp = [idx[0]]
        output_cam = self.returnCAM(self.feature_blobs[0],self.weight_softmax,[idx[0].item()])
        height, width = 28,28
        heatmap = cv2.applyColorMap(cv2.resize(output_cam[0], (width, height)), cv2.COLORMAP_JET)
        heatmap2 = cv2.resize(output_cam[0],(width,height))


        img =img.detach().numpy()
        img2 = img[0]
        img2 = np.transpose(img2,axes=(1,2,0))
        img2=cv2.resize(img2,(28,28))

        #TODO erase
        img2 = cv2.applyColorMap(cv2.resize(output_cam[0], (width, height)), cv2.COLORMAP_JET)


        camsresult = np.array(list(map(resize_image, heatmap, img2)))
        del img_tensor,output_cam,heatmap2,img2,img
        gc.collect()
        result = zip(camsresult, heatmap, probs.detach().cpu().numpy(), idx.detach().cpu().numpy())


with  self.generate_image(img,idx) as result:
      sal_maps_b, heat_map_b, probs_b, preds_b = result

我收到一条错误消息

  

错误'_GeneratorContextManager'对象在
中不能下标   这里----> heatmap = cv2.applyColorMap(cv2.resize(output_cam [0],(width,height)),cv2.COLORMAP_JET)

1 个答案:

答案 0 :(得分:0)

不确定在这里为什么需要contextmanager装饰器,但看起来像是

result = zip(camsresult, heatmap, probs.detach().cpu().numpy(), idx.detach().cpu().numpy())

您应该yield使其contextmanager在引擎盖下做魔术。

yield zip(camsresult, heatmap, probs.detach().cpu().numpy(), idx.detach().cpu().numpy())