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

skimage中rgb2hed函数分块处理矩阵结果异常问题

RGB转HED分块处理结果异常问题

问题描述

我使用skimage库的rgb2hed函数将RGB图像转换为HED颜色空间时,因图像尺寸过大直接转换会出现内存不足的情况,于是编写了分块处理代码,将图像分割为多个区域逐块应用rgb2hed,但得到的结果与直接处理整幅图像差异极大,分块处理后的矩阵几乎全为0。

最小复现代码

import numpy as np
from skimage.color import rgb2hed

np.random.seed(42)
sample = np.random.randint(0, 255, size=(100, 100, 3))

n_splits = 10
x_split_inds = np.linspace(0, sample.shape[0], n_splits + 1, dtype=int)
        
for x in range(len(x_split_inds) - 1):
    x_start = x_split_inds[x]
    x_end = x_split_inds[x + 1]
    sample[x_start:x_end, :, :] = rgb2hed(sample[x_start:x_end, :, :])
        
print(rgb2hed(sample))

print()

print(sample)

输出对比

直接处理整幅图像的结果(截取部分)

[[[1.21016731 0.         0.88195046]
  [1.21016731 0.         0.88195046]
  [1.21016731 0.         0.88195046]
  ...
  [1.21016731 0.         0.88195046]
  [1.21016731 0.         0.88195046]
  [1.21016731 0.         0.88195046]]

 ...

 [[1.21016731 0.         0.88195046]
  [1.21016731 0.         0.88195046]
  [1.21016731 0.         0.88195046]
  ...
  [1.21016731 0.         0.88195046]
  [1.21016731 0.         0.88195046]
  [1.21016731 0.         0.88195046]]]

分块处理后的结果(截取部分)

[[[1 0 0]
  [1 0 0]
  [1 0 0]
  ...
  [1 0 0]
  [1 0 0]
  [1 0 0]]

 ...

 [[1 0 0]
  [1 0 0]
  [1 0 0]
  ...
  [1 0 0]
  [1 0 0]
  [1 0 0]]]

问题原因与解决方法

  • 核心原因:原始sample数组是整数类型,而rgb2hed返回的是浮点类型结果。将浮点值赋值回整数数组时,会自动截断取整,导致大部分小于1的浮点值变为0,仅少数大于等于1的值保留为1。
  • 修复方案:
    1. 提前将原始数组转换为浮点类型,再进行分块处理;
    2. 或创建新的浮点数组存储分块处理结果,避免直接覆盖整数数组。

修改后代码示例

import numpy as np
from skimage.color import rgb2hed

np.random.seed(42)
# 将数组初始化为浮点类型
sample = np.random.randint(0, 255, size=(100, 100, 3)).astype(np.float64)

n_splits = 10
x_split_inds = np.linspace(0, sample.shape[0], n_splits + 1, dtype=int)
        
for x in range(len(x_split_inds) - 1):
    x_start = x_split_inds[x]
    x_end = x_split_inds[x + 1]
    sample[x_start:x_end, :, :] = rgb2hed(sample[x_start:x_end, :, :])
        
# 验证分块处理与直接处理结果一致
direct_result = rgb2hed(np.random.randint(0, 255, size=(100, 100, 3)).astype(np.float64))
print(np.allclose(sample, direct_result))  # 输出True,说明结果匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 18:45:38