sift+svm图像分类

注意:opencv版本为2.4.11,代码也没咋么修改,直接可以用

# -*- coding: utf-8 -*-

"""
Created on Sat Nov 14 23:06:36 2015

@author: Brian

https://github.com/briansrls/SIFTBOW/blob/master/SIFTBOW.py

"""


import cv2
import numpy as np
import os


image_paths = []
path = "E:\\huang\\My_project\\data"


#list of our class names
training_names = os.listdir(path)


training_paths = []
names_path = []
#get full list of all training images
for p in training_names:
    training_paths1 = os.listdir("E:\\huang\\My_project\\data\\"+p)
    for j in training_paths1:
        training_paths.append("E:\\huang\\My_project\\data\\"+p+"\\"+j)
        names_path.append(p)


sift = cv2.SIFT()
print names_path


descriptors_unclustered = []


dictionarySize = 60


BOW = cv2.BOWKMeansTrainer(dictionarySize)


for p in training_paths:
    image = cv2.imread(p)
    gray = cv2.cvtColor(image, cv2.CV_LOAD_IMAGE_GRAYSCALE)
    kp, dsc= sift.detectAndCompute(gray, None)
    BOW.add(dsc)


#dictionary created
dictionary = BOW.cluster()




FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks=50)   # or pass empty dictionary
flann = cv2.FlannBasedMatcher(index_params,search_params)
sift2 = cv2.DescriptorExtractor_create("SIFT")
bowDiction = cv2.BOWImgDescriptorExtractor(sift2, cv2.BFMatcher(cv2.NORM_L2))
bowDiction.setVocabulary(dictionary)
print "bow dictionary", np.shape(dictionary)




#returns descriptor of image at pth
def feature_extract(pth):
    im = cv2.imread(pth, 1)
    gray = cv2.cvtColor(im, cv2.CV_LOAD_IMAGE_GRAYSCALE)
    return bowDiction.compute(gray, sift.detect(gray))


train_desc = []
train_labels = []
i = 0
for p in training_paths:
    train_desc.extend(feature_extract(p))
    if names_path[i]=='gou':
        train_labels.append(1)
    if names_path[i]=='zhu':
        train_labels.append(2)


    i = i+1
print(train_desc)
print "svm items", len(train_desc), len(train_desc[0])
count=0
svm = cv2.SVM()
svm.train(np.array(train_desc), np.array(train_labels))
i=0
j=0


confusion = np.zeros((2,2))
def classify(pth):
    feature = feature_extract(pth)
    p = svm.predict(feature)
    w = int(p)
    confusion[train_labels[count]-1, w-1] = confusion[train_labels[count]-1, w-1] + 1
    
    


for p in training_paths:
    #print(p)
    classify(p)
    count += 1
print(confusion)
def normalizeRows(M):
    row_sums = M.sum(axis=1)
    return M / row_sums
    
confusion = normalizeRows(confusion)


confusion = confusion.transpose()
    
print confusion
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值