把numpy数组保存为图片
时间: 2023-04-09 10:03:42 浏览: 132
可以使用PIL库将numpy数组保存为图片,具体代码如下:
```python
from PIL import Image
import numpy as np
# 创建一个numpy数组
arr = np.random.randint(0, 255, size=(100, 100, 3), dtype=np.uint8)
# 将numpy数组转换为PIL Image对象
img = Image.fromarray(arr)
# 保存图片
img.save('test.png')
```
这样就可以将numpy数组保存为名为test.png的图片。
相关问题
numpy数组保存为jpg格式的图片
要将numpy数组保存为jpg格式的图片,可以使用Python的Pillow库。以下是一个示例代码:
```python
import numpy as np
from PIL import Image
# 生成一个随机的numpy数组
arr = np.random.randint(0, 255, size=(512, 512, 3), dtype=np.uint8)
# 创建Image对象并保存为jpg格式
img = Image.fromarray(arr)
img.save('example.jpg')
```
在上面的代码中,我们首先生成了一个随机的3通道、512x512的numpy数组,并将其转换为Image对象。然后,我们使用Image对象的`save`方法将其保存为jpg格式的图片。如果需要调整图片的压缩质量,可以使用`save`方法的`quality`参数进行设置,例如:
```python
img.save('example.jpg', quality=90)
```
这将保存一个压缩质量为90%的jpg图片。
python将numpy数组存储为图片文件
你可以使用Pillow库来将numpy数组转换为图片文件。以下是一个示例代码:
``` python
from PIL import Image
import numpy as np
# 生成一个随机的numpy数组
arr = np.random.rand(200, 200, 3) * 255
arr = arr.astype(np.uint8)
# 将numpy数组转换为Image对象
img = Image.fromarray(arr)
# 保存图片文件
img.save("output.png")
```
这个代码将生成一个200x200大小的随机numpy数组,并将其转换为一个PIL Image对象。然后,将Image对象保存为名为"output.png"的PNG文件。
阅读全文
相关推荐

















