How to extract Integer from Pytorch Tensor

Question:

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'
Asked By: Hassan

||

Answers:

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

xyxy = [int(e_.item()) for e_ in xyxy]
Answered By: Shai
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.