Python操作指南:从NYU Depth V2数据集mat文件中提取RGB图像和深度图
一、了解 NYU Depth V2 数据集
NYU Depth V2 数据集存储在一个 HDF5 文件(nyu_depth_v2_labeled.mat
)中,包含多个变量。以下是一些关键变量的概览:
images
:RGB 图像,每个样本存储为 (3, H, W) 数组。depths
:处理过的深度图,存储为 (H, W) 数组,单位为米。labels
:语义分割掩码,包含类别 ID。instances
:实例分割掩码,用于标记场景中的对象边界。rawDepths
(原始深度)、names
(类别名称)和 sceneTypes
(场景类型)。本文将重点提取 images
和 depths
,并将它们保存为 PNG 文件,用于可视化或进一步处理。
二、前置条件
在开始之前,请确保安装以下 Python 库:
pip install h5py numpy pillow
h5py
:用于读取 .mat
文件(HDF5 格式)。numpy
:用于数组操作。PIL
(Pillow):用于将数组转换为图像并保存。你还需要下载 NYU Depth V2 数据集。从官方网站 获取 nyu_depth_v2_labeled.mat
,并记录其文件路径。
三、核心代码:提取 RGB 和深度数据
以下是一个 Python 脚本,用于处理 .mat
文件,提取 RGB 图像和深度图,并保存为 PNG 文件:
import h5py
import numpy as np
from PIL import Image
import os
# 定义路径
file_path = r"你的文件路径\nyu_depth_v2_labeled.mat" # 替换为实际路径
rgb_output_dir = "RGB"
depth_output_dir = "Depth"
os.makedirs(rgb_output_dir, exist_ok=True)
os.makedirs(depth_output_dir, exist_ok=True)
# 打开 HDF5 文件
with h5py.File(file_path, 'r') as f:
# 检查数据集是否存在
if 'images' not in f or 'depths' not in f:
print("❌ 未找到所需数据集 ('images' 或 'depths')!")
exit()
# 加载数据集
images = f['images']
depths = f['depths']
num_samples = images.shape[0]
print(f"📂 发现 {num_samples} 个样本。图像形状:{images.shape},深度图形状:{depths.shape}")
# 处理每个样本
for i in range(num_samples):
try:
# 处理 RGB 图像
rgb_data = np.array(images[i]) # 形状:(3, H, W)
if rgb_data.shape[0] == 3:
rgb_data = np.transpose(rgb_data, (1, 2, 0)) # 转为 (H, W, 3)
if rgb_data.dtype != np.uint8:
rgb_data = ((rgb_data - rgb_data.min()) * 255 / (rgb_data.max() - rgb_data.min())).astype(np.uint8)
rgb_img = Image.fromarray(rgb_data, mode='RGB')
rgb_path = os.path.join(rgb_output_dir, f"image_{i:04d}_color.png")
rgb_img.save(rgb_path)
print(f"✅ 已保存 RGB:{rgb_path}")
# 处理深度图
depth_data = np.array(depths[i]) # 形状:(H, W)
if depth_data.ndim != 2:
print(f"⚠️ 跳过深度图 {i}:形状异常 {depth_data.shape}")
continue
# 为可视化将深度归一化到 0-255
depth_data = ((depth_data - depth_data.min()) * 255 / (depth_data.max() - depth_data.min())).astype(np.uint8)
depth_img = Image.fromarray(depth_data, mode='L') # 灰度图
depth_path = os.path.join(depth_output_dir, f"image_{i:04d}_depth.png")
depth_img.save(depth_path)
print(f"✅ 已保存深度图:{depth_path}")
except Exception as e:
print(f"❌ 处理样本 {i} 时出错:{e}")
3.1.代码工作原理
- 文件设置:使用
h5py
打开.mat
文件,并创建输出目录(RGB/
和Depth/
)。 - 数据集验证:检查
'images'
和'depths'
是否存在。 - RGB 处理:
- 加载每个 RGB 图像为 (3, H, W) 数组。
- 转置为 (H, W, 3),以适配 PIL。
- 如果必要,归一化为
uint8
(0-255),然后保存为 PNG。 - 深度处理:
- 加载每个深度图为 (H, W) 数组。
- 为可视化归一化到 0-255(注意:这会丢失原始深度比例)。
- 保存为灰度 PNG(
mode='L'
)。 - 错误处理:捕获并报告处理过程中的任何问题。
3.2.输出结果
运行脚本后,你将得到:
RGB/image_0000_color.png
, RGB/image_0001_color.png
等。Depth/image_0000_depth.png
, Depth/image_0001_depth.png
等。RGB 图像看起来像普通照片,而深度图是灰度图像,亮度表示距离(越暗越近,越亮越远)。
四、小贴士与变体
images[i]
),避免大数据集导致的内存问题。.npy
文件:
np.save(f"Depth/image_{i:04d}_depth.npy", depths[i])
'labels'
,可以参考深度图代码,但直接保存类别 ID 或使用 colormap 转换为彩色图像。:04d
(如 image_0001
)补齐索引,便于排序。五、挑战与解决方法
六、总结
通过几行 Python 代码,你就能解锁 NYU Depth V2 数据集中的视觉和空间信息。这个脚本为预处理 RGB 图像和深度图奠定了基础,但数据集还有更多潜力——语义标签、实例掩码、场景元数据等。尝试根据你的项目需求扩展它,无论是训练模型还是探索室内 3D 感知。
作者:Hello.Reader