You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PIL将非线性格式RGB深度图通过自定义调色板转灰度图?

解决伪彩色深度图转对应灰度深度图的方案

这类伪彩色深度图是通过自定义颜色映射将深度数值编码成RGB的,直接用PIL的常规转灰度方法没用,得先建立RGB到深度值的映射关系,再逐个像素转换。

核心步骤

  • 从调色板图中提取颜色与对应深度灰度值的映射
    调色板是横向渐变条,取其中间一行的所有像素,每个位置的RGB对应一个深度灰度值(比如从左到右对应0~255的深度等级)
  • 遍历目标深度图的每个像素,通过映射表把RGB转换成对应的深度灰度值

代码实现

import os
from PIL import Image

def build_color_depth_map(palette_path):
    # 打开调色板图,取中间行的像素建立映射
    palette_img = Image.open(palette_path).convert("RGB")
    width, height = palette_img.size
    # 取中间一行的像素
    middle_row = height // 2
    color_map = {}
    # 遍历每行的像素,x坐标对应深度灰度值(0~255)
    for x in range(width):
        r, g, b = palette_img.getpixel((x, middle_row))
        # 把RGB元组作为键,对应灰度值(按x位置归一化到0-255)
        gray_value = int((x / width) * 255)
        color_map[(r, g, b)] = gray_value
    return color_map

def convert_depth_rgb_to_gray(img_path, color_map):
    img = Image.open(img_path).convert("RGB")
    width, height = img.size
    # 创建新的灰度图
    gray_img = Image.new("L", (width, height))
    pixels = gray_img.load()
    # 逐个像素转换
    for y in range(height):
        for x in range(width):
            r, g, b = img.getpixel((x, y))
            # 用映射表找对应的灰度值,找不到的话用默认值(比如0)
            pixels[x, y] = color_map.get((r, g, b), 0)
    return gray_img

# 配置路径
directory = "folder/path"
palette_path = "custom-scale/path"

# 建立颜色-深度映射
color_depth_map = build_color_depth_map(palette_path)

# 批量处理目录下的图片
for filename in os.listdir(directory):
    if filename.endswith((".jpg", ".png")):
        file_path = os.path.join(directory, filename)
        gray_img = convert_depth_rgb_to_gray(file_path, color_depth_map)
        gray_img.save(file_path)

补充说明

  • 如果你的调色板是纵向渐变,把代码里取中间行的逻辑改成取中间列即可
  • 要是调色板对应的深度范围不是0~255,可调整gray_value的计算逻辑(比如根据实际深度区间做映射)
  • 批量处理前建议备份原文件,避免覆盖错误

内容的提问来源于stack exchange,提问作者Sivloc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 23:13:13