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

使用NUAA数据集分类时遇3D图像转2D错误,求NumPy解决方案

解决LBP特征提取时3D数组转2D的报错问题

问题根源

你用的NUAA数据集里的图像是3通道彩色图(形状一般是(高度, 宽度, 3)),但local_binary_pattern函数只接受单通道的2D数组,直接传入3D数组就会触发报错。另外代码里w, h=sample.size也有问题——如果sample是PIL图像,size是(宽, 高),但转成numpy数组后,image.shape是(高, 宽, 3),这里的宽高赋值逻辑会混乱。

两种修复方案

方案1:将彩色图转为灰度图处理

如果你的任务不需要彩色信息,直接转灰度图是最简单的方式:

class to_LBP():
    '''class to calculate LBP'''

    def __init__(self, n_points_radius, method):
        self.n_points = n_points_radius
        self.method = method       
        self.channels = len(self.n_points) 
        self.kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]])
    

    def __call__(self, sample):       
        # 处理PIL图像转numpy数组,并转为灰度图
        if isinstance(sample, Image.Image):
            image = np.array(sample.convert('L'))  # 转灰度图
        else:
            # 如果已经是numpy数组,直接转灰度(用加权平均)
            image = np.dot(sample[...,:3], [0.2989, 0.5870, 0.1140])
        
        h, w = image.shape  # 这里用shape取宽高才对
        temp = np.zeros((self.channels, h, w))
        
        image = cv2.filter2D(image, -1, self.kernel)    
        for idx, values in enumerate(self.n_points):             
            lbp = local_binary_pattern(image, values[0], values[1], self.method)              
            temp[idx] = lbp      
        return (temp, image)

方案2:对每个通道分别提取LBP

如果需要保留彩色通道的特征,可以对R、G、B三个通道分别计算LBP,再合并结果:

class to_LBP():
    '''class to calculate LBP'''

    def __init__(self, n_points_radius, method):
        self.n_points = n_points_radius
        self.method = method       
        self.channels = len(self.n_points) 
        self.kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]])
    

    def __call__(self, sample):       
        # 转numpy数组
        image = np.array(sample)
        if len(image.shape) == 3:
            h, w, _ = image.shape
        else:
            h, w = image.shape
        
        temp = np.zeros((self.channels * 3, h, w))  # 每个LBP参数对应3个通道
        
        # 对每个通道分别处理
        for channel_idx in range(3):
            single_channel = image[..., channel_idx]
            single_channel = cv2.filter2D(single_channel, -1, self.kernel)
            
            for lbp_idx, values in enumerate(self.n_points):             
                lbp = local_binary_pattern(single_channel, values[0], values[1], self.method)              
                temp[channel_idx * self.channels + lbp_idx] = lbp      
        return (temp, image)

额外注意点

  • 确认local_binary_pattern是从skimage.feature导入的,导入语句要加:from skimage.feature import local_binary_pattern
  • 测试时打印image.shape,确保进入LBP函数前是(h, w)的2D数组,避免再触发通道错误

内容的提问来源于stack exchange,提问作者S M Sarwar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 18:32:30