convert float image array to int in PIL via Image.fromarray

Viewed 2758

I have a PyTorch tensor of shape 3,256,256 where 3 is the number of channels and the image dimensions are 256, with all float values.

I am trying to feed this into the network and use PIL to do some transforms. To this end, I do:

img = Image.fromarray((255*imgs[i]).numpy().astype(np.uint8))

but I get:

TypeError: Cannot handle this data type: (1, 1, 256), |u1

When I check the output of (255*imgs[i]).numpy().astype(np.uint8), I do however see, for example:

[[[ 62  57  59 ...  63  46  36]
  [ 72  71  67 ...  80  76  82]
  [ 58  63  63 ... 145 152 169]
  ...
  [238 240 243 ...   7   7   7]
  [241 239 240 ...   5   5   6]
  [241 243 242 ...   4   3   5]]

 [[ 83  78  80 ...  86  70  61]
  [ 91  90  85 ...  95  93  98]
  [ 80  83  80 ... 141 150 168]
  ...
  [176 178 181 ...  14  14  14]
  [177 176 178 ...  15  15  17]
  [179 180 180 ...  13  13  15]]

 [[147 141 143 ... 150 136 128]
  [147 149 148 ... 154 149 154]
  [141 149 148 ... 178 182 196]
  ...
  [129 131 134 ...  43  43  43]
  [130 130 131 ...  45  45  47]
  [133 134 133 ...  44  44  46]]]

I am not an image expert by a long shot, and I am struggling to troubleshoot this issue now.

1 Answers

You need to match the order of dimensions, not only the dtype. PIL.Image expects its RGB images to be of shape hxwx3 - channel dimension last, while prefer to represent images as 3xhxw - channel dimension first.

Thus you need:

img = Image.fromarray((255*imgs[i]).numpy().astype(np.uint8).transpose(1, 2, 0))
Related