Search code examples
pythonpython-imaging-library

PIL TypeError: Cannot handle this data type: (1, 1, 299, 3), |u1


So, I am trying to generate patches of the image, but I am getting this really weird error, and I don't know how to fix it. Can anyone assist me?

Well, first when checking the other questions on this platform, I thought I had errors in my dimensions and tried to fix it but, it changed nothing...

import numpy as np
from patchify import patchify
from PIL import Image
import cv2
#ocean =Image.open("ocean.jpg") #612 X 408
ocean =cv2.imread("/kaggle/input/supercooldudeslolz/new_300.jpg")
ocean = cv2.resize(ocean, (1495, 2093))
print(ocean.size)
ocean = np.asarray(ocean)
patches =patchify(ocean,(299,299, 3),step=299)
print(patches.shape)
for i in range(patches.shape[0]):
    for j in range(patches.shape[1]):
        patch = patches[i, j]
        patch = Image.fromarray(patch)
        num = i * patches.shape[1] + j
        patch.save(f"patch_{num}.jpg")

this is errror:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
File /opt/conda/lib/python3.10/site-packages/PIL/Image.py:3089, in fromarray(obj, mode)
   3088 try:
-> 3089     mode, rawmode = _fromarray_typemap[typekey]
   3090 except KeyError as e:

KeyError: ((1, 1, 299, 3), '|u1')

The above exception was the direct cause of the following exception:

TypeError                                 Traceback (most recent call last)
Cell In[16], line 15
     13 for j in range(patches.shape[1]):
     14     patch = patches[i, j]
---> 15     patch = Image.fromarray(patch)
     16     num = i * patches.shape[1] + j
     17     patch.save(f"patch_{num}.jpg")

File /opt/conda/lib/python3.10/site-packages/PIL/Image.py:3092, in fromarray(obj, mode)
   3090     except KeyError as e:
   3091         msg = "Cannot handle this data type: %s, %s" % typekey
-> 3092         raise TypeError(msg) from e
   3093 else:
   3094     rawmode = mode

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

now my output about patches.shape prints this shape:

(7, 5, 1, 299, 299, 3)

Solution

  • The shape of patches should be (3,7,1,299,299). There's an extra dimension in there. So, replace

        patch = patches[i,j]
    

    with

        patch = patches[i,j,0]
    

    Also note another, more "Pythonic" way to do this:

    num = 0
    for row in patches:
        for col in row:
            patch = Image.fromarray(col[0])
            patch.save(f"patch_{num}.jpg")
            num += 1