请把一张图片和2个和图片大小一样的数据打包成h5数据
时间: 2023-05-22 11:03:58 浏览: 81
您可以使用Python的h5py库将一张图片和两个同样大小的数据打包成.h5数据文件。以下是示例代码:
```python
import h5py
import numpy as np
from PIL import Image
# Load the image
image = np.array(Image.open("image.jpg"))
# Generate two random arrays with the same size as the image
array1 = np.random.rand(*image.shape)
array2 = np.random.rand(*image.shape)
# Create the .h5 file and save the arrays and image as datasets
with h5py.File("data.h5", "w") as f:
f.create_dataset("image", data=image)
f.create_dataset("array1", data=array1)
f.create_dataset("array2", data=array2)
```
此代码将生成一个名为“data.h5”的文件,其中包含名称为“image”、“array1”和“array2”的三个数据集。您可以根据需要重命名它们,并使用相应的键访问它们。
请注意,此代码仅适用于大小相同的数据和图像,如果您需要将不同大小的数据打包成.h5文件,请修改代码。
相关问题
请用h5py将120个图片,每个图片宽度600长度600,打包成h5数据
非常感谢您的问题!以下是使用h5py将120张600x600的图片打包成h5数据的Python代码示例:
``` python
import h5py
import numpy as np
from PIL import Image
import os
# 图像数据存储路径
data_folder = "path/to/image/folder"
# 读取所有图像数据并转换为numpy数组
data = []
for i in range(1, 121):
# 图像文件名格式为 img_001.jpg ~ img_120.jpg
img_file = os.path.join(data_folder, f"img_{i:03}.jpg")
img = Image.open(img_file).convert("RGB")
img = np.array(img)
data.append(img)
# 将所有图像数据打包成h5数据
with h5py.File("data.h5", "w") as f:
f.create_dataset("data", data=np.array(data))
```
这段代码首先读取存储在 `data_folder` 中的所有图像数据,并将它们转换为numpy数组。然后使用h5py库创建一个新的h5文件,并将所有图像数据保存在一个名为"data"的数据集中。
用pycharm从h5文件中把AUU-sewer数据集转换为图片
你可以使用以下代码将AUU-sewer数据集从h5文件转换为图片:
```python
import h5py
import numpy as np
import cv2
# Load the h5 file
with h5py.File('path/to/auu-sewer.h5', 'r') as f:
images = np.array(f['images'])
labels = np.array(f['labels'])
# Convert the images to RGB format and save as png files
for i, image in enumerate(images):
image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
cv2.imwrite(f'path/to/save/image_{i}.png', image)
```
请注意,你需要将代码中的路径替换为你自己的路径。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)