PIL 类型错误:无法处理此数据类型:(1, 1, 299, 3),|u1

问题描述 投票:0回答:1

所以我试图生成图像的补丁,但我遇到了这个非常奇怪的错误,而且我不知道如何修复它。有人可以帮助我吗?

好吧,首先在这个平台上检查其他问题时,我以为我的尺寸有错误并尝试修复它,但是,它没有改变任何东西......

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")

这是错误:

---------------------------------------------------------------------------
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

现在我关于 patch.shape 的输出打印出这个形状:

(7, 5, 1, 299, 299, 3)
python python-imaging-library
1个回答
0
投票

patches
的形状应该是
(3,7,1,299,299)
。 那里有一个额外的维度。 所以,更换

    patch = patches[i,j]

    patch = patches[i,j,0]
© www.soinside.com 2019 - 2024. All rights reserved.