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

HOG特征结合KNN分类报错:期望2D数组却得到1D数组

HOG+KNN分类器报错:预期2D数组,实际得到1D数组

问题说明

运行HOG特征结合KNN分类器的代码时,数据拆分后输入KNN环节触发报错:

ValueError: Expected 2D array, got 1D array instead
中文翻译:值错误:预期2D数组,实际得到1D数组

尝试将data转为np.array(data)、用reshape(1,-1)调整形状均未解决问题。

问题根源

  1. HOG参数未定义:代码中调用hog函数时用到的orientations、pixels_per_cell、cells_per_block未预先定义,会先触发NameError,这是前置问题。
  2. 特征维度不一致:不同图像尺寸不同,导致提取的HOG特征向量长度不统一,最终data列表转成数组后不是标准的(样本数, 特征数)2D结构,而是包含不同长度数组的1D数组,不符合KNN输入要求。

解决方案

1. 定义HOG关键参数

在调用hog函数前,明确参数值(示例为HOG常用配置):

orientations = 9
pixels_per_cell = (8, 8)
cells_per_block = (2, 2)

2. 统一所有图像尺寸

提取HOG特征前,将所有图像resize到相同尺寸,确保特征向量长度一致:

gray = gray.resize((64, 128))  # 转灰度后添加该步骤,尺寸可根据需求调整

3. 正确转换特征数据为2D数组

特征提取完成后,直接将data转为numpy数组,确保结构为(n_samples, n_features):

data = np.array(data)

修改后的完整代码

import os
import cv2
import matplotlib.pyplot as plt
import re
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.svm import LinearSVC
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from skimage.feature import hog
from PIL import Image

# 定义HOG参数
orientations = 9
pixels_per_cell = (8, 8)
cells_per_block = (2, 2)

image_paths=[] # 存储所有图像路径
for dirname, _, filenames in os.walk('MICC-F220'):
    for filename in filenames:
        image_paths.append(os.path.join(dirname, filename))

original_images=[]
tampered_images=[]

for path in image_paths:
    if 'tamp' in path:              
        tampered_images.append(path)
    else:
        original_images.append(path)
tampered_images.sort()
original_images.sort()
print(len(original_images),len(tampered_images))

data= []
labels = []

# 提取HOG特征并打标签
for file in original_images: 
    img = Image.open(file)
    gray = img.convert('L') # RGB转灰度图
    gray = gray.resize((64, 128))  # 统一图像尺寸
    fd = hog(gray, orientations=orientations, pixels_per_cell=pixels_per_cell, 
             cells_per_block=cells_per_block, block_norm='L2', feature_vector=True)
    data.append(fd)
    labels.append(0)

for file in tampered_images: 
    img = Image.open(file) 
    gray = img.convert('L')
    gray = gray.resize((64, 128))  # 统一图像尺寸
    fd = hog(gray, orientations=orientations, pixels_per_cell=pixels_per_cell, 
             cells_per_block=cells_per_block, block_norm='L2', feature_vector=True)
    data.append(fd)
    labels.append(1)

# 转换为标准2D特征数组
data = np.array(data)
le = LabelEncoder()
labels = le.fit_transform(labels)

# 拆分训练测试集
trainData, testData, trainLabels, testLabels = train_test_split(data, labels, test_size=0.20, random_state=42) 

print(" Training KNN classifier...")
model = KNeighborsClassifier()
model.fit(trainData, trainLabels)

# 评估分类器
print(" Evaluating classifier on test data ...")
predictions = model.predict(testData)
print(classification_report(testLabels, predictions))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 08:15:31