How to infernece pytorch model on list of images?

I have a list of numpy arrays each one represent an image and I want to predict all of them at same time.
Here’s my code:
Screenshot from 2023-05-11 14-41-01
But I got this error:
imgs = torch.stack(imgs, 0)
TypeError: expected Tensor as element 0 in argument 0, but got numpy.ndarray

PyTorch doesnt work directly on numpy arrays, you need to convert them to torch tensors first, so as a first line you can add something like imgs = [torch.from_numpy(img) for img in imgs]

ok but the imgs is still a python list and can’t be fed to tranform or to the model itself

def predict(imgs, device):
    with torch.no_grad():
        imgs = [torch.from_numpy(img) for img in imgs]
        imgs = torch.stack(imgs).to(device)
        out = model(imgs).detach().cpu().numpy()
    return out
1 Like