Search code examples
pythonpytorchtensor

How to extract Integer from Pytorch Tensor


This is a part of code... VSCODE declares variable > xyxy as 'list'

                for *xyxy, conf, cls in reversed(det):
                if save_txt:  # Write to file
                    xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywh
                    line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh)  # label format
                    with open(txt_path + '.txt', 'a') as f:
                        f.write(('%g ' * len(line)).rstrip() % line + '\n')

                if save_img or view_img:  # Add bbox to image
                    label = f'{names[int(cls)]} {conf:.2f}'
                    plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=1)
                
                else : 
                    pass # 

        # Print time (inference + NMS)
        print(f'{s}Done. ({(1E3 * (t2 - t1)):.1f}ms) Inference, ({(1E3 * (t3 - t2)):.1f}ms) NMS')
        #print(xyxy_custom = xyxy.numpy()`


         

Printing variable xyxy gives this output (possibly pytorch tensor)

[tensor(513., device='cuda:0'), tensor(308., device='cuda:0'), tensor(661., device='cuda:0'), tensor(394., device='cuda:0')]

I want to extract integers from this list (for example output should be [513,308,661,394]

i have tried print(xyxy.list()) or print(xyxy.numpy(). this gives an error

AttributeError: 'list' object has no attribute 'list'

Solution

  • You can convert the elements of the list into integers using .item():

    xyxy = [int(e_.item()) for e_ in xyxy]