2016-04-29 41 views
3

我想使用一些圖像SIFT的檢測和計算關鍵點和描述符,然後用KNN分類爲它們進行分類:Python。 K近鄰類型錯誤:樣本數據類型= 17不支持

這是我的小碼:

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張名單,因此該循環檢測並計算柯每個圖像的y點和描述符。我給你一些images.Thanks

enter image description here

enter image description here

enter image description here

+0

你可以包含縮減的樣本日期集來證明,maby三張圖片嗎? – tfv

+0

如果代碼完整(包括導入語句,文件名等)和可用的數據以便我們可以複製它,您可能會得到更快的響應。 – tfv

+0

@tfv我編輯了這篇文章。覈實。感謝您的建議 – Jose

回答

0

在任何情況下,我的感覺是你缺少一個行

import numpy as np 

sift = cv2.SIFT() 

代碼中的某處。

對我來說,下面附上了實際再現您問題的代碼(包括由於我的版本CV 2.4.12所做的一些更改)。

但是,我擔心你選擇的方法根本不適用於K最近鄰(KNN)。 KNN測量屬於不同樣本的特徵向量之間的距離。然而,對於所有特徵向量,矢量的每個分量需要具有相同的含義(例如,一個特徵是圖像的平均亮度值)。因此該功能始終需要顯示在您的vecort的相同位置。

在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) 
+0

哦,我明白了,是的,我忘了在代碼中包含這些行,我的錯誤。謝謝,@tfv清除了很多東西,謝謝。 OpenCV的版本是3.1.0,帶有來自Itseez/opencv_contrib github存儲庫的額外模塊 – Jose

相關問題