# PIL Image to FloatTensor (uint16 to float32)

**URL:** <https://discuss.pytorch.org/t/pil-image-to-floattensor-uint16-to-float32/54577>\
**Category:** Uncategorized\
**Created:** [August 28, 2019, 2:29pm UTC](https://discuss.pytorch.org/t/pil-image-to-floattensor-uint16-to-float32/54577 "2019-08-28T14:29:05Z")\
**Posts on this page:** 1\
**Showing post:** 1

<div class="post-metadata">

**Author:** ![fumoffu947](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/f/439d5e/32.png) [@fumoffu947](https://discuss.pytorch.org/u/fumoffu947)\
**Post date:** [August 28, 2019, 2:29pm UTC](https://discuss.pytorch.org/t/pil-image-to-floattensor-uint16-to-float32/54577/1 "2019-08-28T14:29:05Z")

</div>

I have tif images that have a data type of **unsigned int 16 bit**.  
PIL can read these images without problem and have the correct type.  
But as my custom data set reader reads this tif image and then tries to contert it to a tensor, for the normal normalization and then usage in the network, things goes wrong.

I read the image which have values from zero to the max value of **uint16**.  
then i use the standard way transformation:

```auto
image_transform = transfroms.Compose([
          transforms.ToTensor(),
          transforms.Normalize((value,), (value,))
)]

```

This code will result in errors.  
As the ToTensor function will convert images with value between [0, 255] and of some specific format to a tensor with values between [0,1] (thus a float tensor).  
But for other images it will keep the same datatype and just convert the values.

So for this case it will take the data type closes to a **unsigned int16** which is a **signed int16** …  
This will result in overflows and non correct data.

**So the question is how to do it an easy (using torch) and fast way?**

They way i do it is to first convert to a numpy array; then convert to a signed **float 32** then to a float tensor, that can be used as normal.

```auto
image_fp = open("filepath", "rb")
image = PIL.Image.open(image_fp)
im_arr = np.array(image)
im_arr32 = im_arr.astype(np.float32)
im_tensor = torch.tensor(im_arr32)
im_tensor = im_tensor.unsqueeze(0)

```

And this results in this ugly lambda:

```auto
image_transform = transfroms.Compose([
          transforms.Lambda(lambda image: torch.tensor(numpy.array(image).astype(numpy.float32)).unsqueeze(0)),
          transforms.Normalize((value,), (value,))
)]

```

(All these conversion will impact the loading time with large datasets)

**[edit]**  
So the differense that can save alot of time is to use:

```auto
transforms.Lambda(lambda image: torch.from_numpy(numpy.array(image).astype(numpy.float32)).unsqueeze(0))

```

instead of the torch.tensor function

---

_[View the full topic](https://discuss.pytorch.org/t/pil-image-to-floattensor-uint16-to-float32/54577)._
