Converting a torch.Tensor to a float pointer and vice versa

51 Views Asked by At

I have an image x (as a torch.Tensor) of shape (512, 512, 3) (the first dimension being the color channel count). When I save it as an *.exr-file, using imageio.imsave, the output is the correct image:

enter image description here

I need to pass a pointer to x to a C++-library. I get the pointer via p = ctypes.cast(x.data_ptr(), ctypes.POINTER(ctypes.c_float)). I also need to convert pointers and I'm doing so by the as_tensor function from this answer:

def as_tensor(pointer, shape, torch_type):
    return torch.frombuffer((pointer._type_ * prod(shape)).from_address(ctypes.addressof(pointer.contents)), dtype = torch_type).view(*shape)

Now, when I write y = as_tensor(p, x.shape, torch.float) and save this an *.exr, I get the previous image repeated in a 3x3 grid (each row being one of the 3 channels, I guess):

enter image description here

What is going on here? What I would expected is clearly x = y (in terms of the data).

0

There are 0 best solutions below