ValueError: Images of type float must be between -1 and 1.

背景:模型处理完的图片是numpy格式,现要将此数据专为图片,采用PIL或者imageio库进行操作,如今出现上述问题。gradio内部是有处理numpy格式的,只需对接即可。

愿我们终有重逢之时,而你还记得我们曾经讨论的话题。

QQ group 868373192

QQ second group 277356808

解决方案1:

### 问题描述

你在使用 `gradio` 库时遇到了一个错误,错误信息如下:

```
ValueError: Images of type float must be between -1 and 1.
```

这个错误表明你正在尝试将一个浮点类型的图像数组转换为 `PIL` 图像,但该图像数组的值不在 `-1` 到 `1` 的范围内。`gradio` 库要求浮点类型的图像数组的值必须在 `-1` 到 `1` 之间。

### 解决方案

你可以通过以下几种方法来解决这个问题:

#### 1. 检查图像数组的值范围

首先,确保你的图像数组的值在 `-1` 到 `1` 之间。如果图像数组的值超出了这个范围,你可以通过以下方式进行归一化:

```python
import numpy as np

# 假设你的图像数组是 image_array
image_array = (image_array - image_array.min()) / (image_array.max() - image_array.min()) * 2 - 1
```

这段代码将图像数组的值归一化到 `-1` 到 `1` 之间。

#### 2. 转换图像数组的类型

如果你不需要浮点类型的图像数组,可以将图像数组转换为 `uint8` 类型,这样就不需要归一化到 `-1` 到 `1` 之间:

```python
image_array = (image_array * 255).astype(np.uint8)
```

这段代码将图像数组的值缩放到 `0` 到 `255` 之间,并将其类型转换为 `uint8`。

#### 3. 修改 `gradio` 库的代码

如果你希望 `gradio` 库支持超出 `-1` 到 `1` 范围的浮点图像数组,你可以修改 `gradio` 库的代码。找到 `processing_utils.py` 文件中的 `_convert` 函数,并修改其中的检查逻辑:

```python
def _convert(image_array, dtype, force_copy=False):
    if dtype == np.uint8:
        if image_array.dtype == np.uint8:
            return image_array
        return np.clip(image_array, 0, 255).astype(np.uint8)
    elif dtype == np.float32:
        if image_array.dtype == np.float32:
            return image_array
        return np.clip(image_array, -1, 1).astype(np.float32)
    else:
        raise ValueError("Unsupported dtype")
```

你可以将 `np.clip(image_array, -1, 1)` 修改为 `np.clip(image_array, -255, 255)`,以支持更大范围的浮点数。

### 总结

根据你的需求选择合适的解决方案。如果你需要保持浮点类型的图像数组,确保其值在 `-1` 到 `1` 之间;如果你不需要浮点类型,可以将其转换为 `uint8` 类型;或者你也可以修改 `gradio` 库的代码以支持更大范围的浮点数。

解决方案2:

import PIL
from PIL import Image,ImageFile
    out = np.clip(out, 0, 255).astype(np.uint8)
    img = Image.fromarray(out[:, :, ::-1])

模型推理后的numpy大多数是BGR的格式,要换成RGB,故而要进行

out[:, :, ::-1]

这样gradio显示才会正常。

猜你喜欢

转载自blog.csdn.net/SPESEG/article/details/143234823