蟒蛇。 K最近邻居TypeError:不支持样本数据类型= 17

时间:2016-04-29 21:19:18

标签: python opencv sift knn

我尝试使用SIFT对一些图像进行分类以检测和计算关键点和描述符,然后使用KNN对它们进行分类:

这是我的小代码:

import os
import cv2

## Prepare images files
rootpath = '/Some/Directory'
files = []
for filedir, dirs, filess in os.walk(rootpath):
    for filename in filess:
        pathfile = os.path.join(filedir, filename)
        files.append(pathfile) 

## Detect keypoints and compute descriptors for train images
kp_train = []
dsc_train = []
for file in files:
    ima = cv2.imread(file)
    gray=cv2.cvtColor(ima,cv2.COLOR_BGR2GRAY)
    kpts, des = sift.detectAndCompute(gray, None) 
    kp_train.append(kpts)
    dsc_train.append(des)

## Train knn
dsc_train = np.array(dsc_train)
responses = np.arange(len(kp_train),dtype = np.float32)
knn = cv2.ml.KNearest_create()
knn.train(dsc_train, cv2.ml.ROW_SAMPLE, responses)

但我有点陷入下一个错误

>>> knn.train(dsc_train,cv2.ml.ROW_SAMPLE,responses)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: dsc_train data type = 17 is not supported

文件是包含10个图像的列表,因此循环检测并计算每个图像的关键点和描述符。我给你一些图片。谢谢

enter image description here

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

无论如何,我的感觉是你错过了一行

import numpy as np

sift = cv2.SIFT()

代码中的某处。

对我来说,下面附有实际再现问题的代码(包括因我的CV 2.4.12版本而导致的一些更改)。

但是,我担心你选择的方法根本不适合K最近邻居(KNN)。 KNN测量属于不同样本的特征向量之间的距离。然而,对于所有特征向量,向量的每个分量需要具有相同的含义(例如,一个特征是图像的平均亮度值)。所以这个功能总是需要出现在你的同一个位置。

在SUFT中,您将创建不同图像关键点的坐标。最重要的是,每个图像的特征向量的长度将不同,因此您无法应用kNN。显然,这些坐标作为用于比较不同图像的特征向量的一部分是没有意义的。

import os
import cv2 #Using CV 2.4.12
import numpy as np

## Prepare images files
rootpath = 'images/'
files = []
for filedir, dirs, filess in os.walk(rootpath):
    for filename in filess:
        pathfile = os.path.join(filedir, filename)
        files.append(pathfile) 

print files

## Detect keypoints and compute descriptors for train images
kp_train = []
dsc_train = []
sift = cv2.SIFT()
for file in files:
    ima = cv2.imread(file)
    print file
    gray=cv2.cvtColor(ima,cv2.COLOR_BGR2GRAY)
    kpts, des = sift.detectAndCompute(gray, None) #sift = cv2.xfeatures2d.SIFT_create()
    kp_train.append(kpts)
    dsc_train.append(des)

## Train knn
dsc_train = np.array(dsc_train)
responses = np.arange(len(kp_train),dtype = np.float32)
knn = cv2.KNearest()

#Next line does not work:
knn.train(dsc_train, responses)