日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

pythonsvm图像分类_python图像处理之sift-kmeans-SVM图像分类

發布時間:2025/4/5 python 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 pythonsvm图像分类_python图像处理之sift-kmeans-SVM图像分类 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

原文代碼在python3.0或者opencv版本不同下跑不通。

我這里做一些改動,自行參考,文筆有限。

改動點1:圖像輸入自定義,不再固定名稱

改動點2:解決找不到sift、svm組件類型問題

改動點3:解決svm訓練的標簽錯誤問題

改動點4:解決導入不了svm模型問題

注意:SVM.train中標簽一定要為整數類型

代碼如下:

import cv2

import numpy as np

import os

TrainSetInfo = {

"car":40,

"city":20,

"dog":30,

"earth":15,

"fireworks":20,

"flowers":20,

"fruits":20,

"glass":20,

"gold":15,

"gun":20,

"plane":40,

"sky":30,

"worldcup":40

}

TestSetInfo = {

"car":119,

"city":59,

"dog":49,

"earth":24,

"fireworks":54,

"flowers":63,

"fruits":78,

"glass":52,

"gold":44,

"gun":44,

"plane":102,

"sky":78,

"worldcup":131

}

def calcSiftFeature(img):

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

sift = cv2.xfeatures2d.SIFT_create(200) # max number of SIFT points is 200

kp, des = sift.detectAndCompute(gray, None)

return des

def calcFeatVec(features, centers):

featVec = np.zeros((1, 50))

for i in range(0, features.shape[0]):

fi = features[i]

diffMat = np.tile(fi, (50, 1)) - centers

sqSum = (diffMat**2).sum(axis=1)

dist = sqSum**0.5

sortedIndices = dist.argsort()

idx = sortedIndices[0] # index of the nearest center

featVec[0][idx] += 1

return featVec

def initFeatureSet():

for name, count in TrainSetInfo.items():

# dir = "D:/GJAI_data/gongjingai_pre/train_1-2-3/" + name + "/"

dir = "TrainSet/" + name + "/"

featureSet = np.float32([]).reshape(0,128)

print("Extract features from training set " + name + "...")

pathDir = os.listdir(dir)

for i in pathDir:

filename = os.path.join('%s%s' % (dir, i))

img = cv2.imread(filename)

des = calcSiftFeature(img)

featureSet = np.append(featureSet, des, axis=0)

featCnt = featureSet.shape[0]

print(str(featCnt) + " features in " + str(count) + " images\n")

# save featureSet to file

filename = "Temp1/features/" + name + ".npy"

np.save(filename, featureSet)

def learnVocabulary():

wordCnt = 50

for name, count in TrainSetInfo.items():

filename = "Temp1/features/" + name + ".npy"

features = np.load(filename)

print("Learn vocabulary of " + name + "...")

# use k-means to cluster a bag of features

criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 0.1)

flags = cv2.KMEANS_RANDOM_CENTERS

compactness, labels, centers = cv2.kmeans(features, wordCnt,None, criteria, 20, flags)

# save vocabulary(a tuple of (labels, centers)) to file

filename = "Temp1/vocabulary/" + name + ".npy"

np.save(filename, (labels, centers))

print("Done\n")

def trainClassifier():

trainData = np.float32([]).reshape(0, 50)

response = np.int32([])

dictIdx = 0

for name, count in TrainSetInfo.items():

# dir = "D:/GJAI_data/gongjingai_pre/train_1-2-3/" + name + "/"

dir = "TrainSet/" + name + "/"

labels, centers = np.load("Temp1/vocabulary/" + name + ".npy")

print("Init training data of " + name + "...")

pathDir = os.listdir(dir)

for i in pathDir:

filename = os.path.join('%s%s' % (dir, i))

img = cv2.imread(filename)

features = calcSiftFeature(img)

featVec = calcFeatVec(features, centers)

trainData = np.append(trainData, featVec, axis=0)

res = np.repeat(dictIdx, count)

response = np.append(response, res)

dictIdx += 1

print("Done\n")

print("Now train svm classifier...")

trainData = np.float32(trainData)

response = response.reshape(-1, 1)

svm = cv2.ml.SVM_create()

svm.setKernel(cv2.ml.SVM_LINEAR)

# svm.train_auto(trainData, response, None, None, None) # select best params

svm.train(trainData,cv2.ml.ROW_SAMPLE,response)

svm.save("svm.clf")

print("Done\n")

def classify():

# svm = cv2.SVM()

# svm = cv2.ml.SVM_create()

svm = cv2.ml.SVM_load("svm.clf")

total = 0; correct = 0; dictIdx = 0

for name, count in TestSetInfo.items():

crt = 0

# dir = "D:/GJAI_data/gongjingai_pre/validation_1-2-3/" + name + "/"

dir = "TestSet/" + name + "/"

labels, centers = np.load("Temp1/vocabulary/" + name + ".npy")

print("Classify on TestSet " + name + ":")

pathDir = os.listdir(dir)

for i in pathDir:

filename = os.path.join('%s%s' % (dir, i))

img = cv2.imread(filename)

features = calcSiftFeature(img)

featVec = calcFeatVec(features, centers)

case = np.float32(featVec)

dict_svm = svm.predict(case)

dict_svm = int(dict_svm[1])

if (dictIdx == dict_svm):

crt += 1

print("Accuracy: " + str(crt) + " / " + str(count) + "\n")

total += count

correct += crt

dictIdx += 1

print("Total accuracy: " + str(correct) + " / " + str(total))

if __name__ == "__main__":

initFeatureSet()

learnVocabulary()

trainClassifier()

classify()

如有疑問,請評論。

總結

以上是生活随笔為你收集整理的pythonsvm图像分类_python图像处理之sift-kmeans-SVM图像分类的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。