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

原始代码:

scipy.misc.toimage(img).save(s, format="png")

因为scipy1.2.0以上没有了.toimage等很多函数。所以运用其他的来代替。

from PIL import Image
Image.fromarray(np.uint8(img).convert('RGB').save(s, format="png")

但是运行会报错误:

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

解决措施:

Image.fromarray(np.uint8(img.transpose(1, 2, 0))).convert('RGB').save(s, format="png")

添加img.transpose(1,2,0)。

原因:我的数据输入格式img是(3,128,128),即是(channel,width,height)。但是使用PIL库处理图像数据时候,需要的格式是(width,height,channel),所以需要进行转换,把(C,W,H)变为(W,H,C)即可。

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这个错误提示是由于Pillow库无法处理多波段的数据类型。在这种情况下,你可以将多波段的数据拆分成单波段的数据,分别转换为Pillow库可以处理的数据类型,然后再将它们合并成多波段数据。可以按照以下步骤修改代码: 1. 将多波段的数据拆分成单波段的数据,使用numpy库的split方法,将数据按照波段维度拆分: ```python import numpy as np # 按照波段维度拆分数据 bands = np.split(da_resampled.values, da_resampled.shape[-1], axis=-1) ``` 2. 将单波段的数据转换为Pillow库可以处理的数据类型,使用numpy库的astype方法将数据类型转换为uint8: ```python # 将每个单波段数据转换为Pillow库可以处理的数据类型 bands = [Image.fromarray(band.squeeze().astype('uint8')) for band in bands] ``` 3. 将转换后的单波段数据合并成多波段数据,使用Pillow库的merge方法将单波段数据合并: ```python # 将单波段数据合并成多波段数据 img = Image.merge('RGB', bands) ``` 最后,使用rio库的write方法将数据和缩略图一起写入到文件中: ```python with rasterio.open(out_root / f'{nc_path.stem}.tif', 'w', driver='GTiff', crs=ref_da.crs, transform=ref_da.transform) as dst: dst.write(da_resampled.values, 1) dst.update_tags(ns='rio', res=str(ref_da.res[0])) # 将分辨率写入文件属性 dst.write(img.tobytes(), 1, photometric='RGB', thumbnail=(256, 256)) # 将缩略图写入文件属性 ``` 这样就可以解决多波段数据类型无法处理的问题了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值