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

如何在灰度图上绘制彩色轮廓且不丢失原始图像信息

报错原因

Clipping input data报错的核心是matplotlib imshow对RGB输入的取值范围有强制要求:浮点型必须在[0,1]区间,整型必须在[0,255]区间。你用img_as_uint导出的原始灰度图是16位无符号整型,最大值1078远超过255,转RGB后三通道依然保留了16位的取值范围,因此触发警告,直接裁剪到[0,255]必然丢失灰度层级信息。

推荐解决方案

方案1:matplotlib分层叠加(完全不修改原始灰度数据,优先选择)

不需要转换灰度图格式,先绘制原始灰度图,再叠加彩色轮廓即可,原始数据全程不会被改动:

# 保留原始灰度数据,不做任何修改
raw_gray = image.detach().numpy()

# 绘制原始灰度图,cmap指定灰度映射,vmin/vmax可根据需求调整显示范围,不影响原始数据
plt.imshow(raw_gray, cmap='gray')

# 叠加绘制各类别彩色轮廓
for cls_idx in range(1, len(include_classes)):
    # 提取对应类别的轮廓,按你自己的轮廓存储逻辑调整索引即可
    current_contours = contours[cls_idx]
    # 转换颜色值为matplotlib兼容的[0,1]浮点格式
    line_color = [c/255 for c in rgb_dict[include_classes[cls_idx]]]
    for cnt in current_contours:
        # 提取轮廓坐标点
        x_coords = cnt[:, 0, 0]
        y_coords = cnt[:, 0, 1]
        plt.plot(x_coords, y_coords, color=line_color, linewidth=1)

plt.axis('off')
plt.show()

方案2:生成显示专用副本,原始数据单独留存

如果必须使用OpenCV的drawContours接口绘制轮廓,可以单独生成一个归一化到[0,255]的显示用副本,原始灰度数据单独存储不参与绘制流程:

# 单独留存原始灰度数据,全程不改动
raw_gray = image.detach().numpy()

# 生成显示用的8位RGB副本,线性拉伸灰度范围到[0,255],不会丢失灰度层级
display_img = cv2.normalize(raw_gray, None, 0, 255, cv2.NORM_MINMAX, dtype=cv2.CV_8U)
display_img = cv2.cvtColor(display_img, cv2.COLOR_GRAY2RGB)

# 在副本上绘制轮廓
for cls_idx in range(1, len(include_classes)):
    cv2.drawContours(display_img, contours[cls_idx], -1, rgb_dict[include_classes[cls_idx]], 1)

# 显示
plt.imshow(display_img)
plt.axis('off')
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 12:24:03