資源簡介
HOG提取特征,svm分類,python語言實現
代碼片段和文件信息
#?-*-?coding=utf-8?-*-
import?glob
import?time
from?PIL?import?Image
from?skimage.feature?import?hog
import?numpy?as?np
import?os
import?joblib
from?sklearn.svm?import?LinearSVC
#訓練集圖片的位置
train_image_path?=?‘/home/icelee/Downloads/dataset/small_shixun/‘
#測試集圖片的位置
test_image_path?=?‘/home/icelee/Downloads/dataset/small_shixun/‘
#訓練集標簽的位置
train_label_path?=?‘/home/icelee/Downloads/dataset/mydata.txt‘
#測試集標簽的位置
test_label_path?=?‘/home/icelee/Downloads/dataset/test.txt‘
size?=?128
train_feat_path?=?‘train/‘
test_feat_path?=?‘test/‘
model_path?=?‘model/‘
#獲得圖片列表
def?get_image_list(filePathnameList):
????img_list?=[]
????for?name?in?nameList:
????????img_list.append(Image.open(filePath+name))
????return?img_list
#提取特征并保存
def?get_feat(image_listname_listlabel_listsavePathsize):
????i?=?0
????for?image?in?image_list:
????????image?=?np.reshape(image?(size?size?3))
????????gray?=?rgb2gray(image)/255.0
????????#這句話根據你的尺寸改改
????????fd?=?hog(gray?orientations=18?pixels_per_cell=[1616]?cells_per_block=[44]?visualise=False?transform_sqrt=True)
????????fd?=?np.concatenate((fd?[label_list[i]]))
????????fd_name?=?name_list[i][0:6]+‘.feat‘
????????fd_path?=?os.path.join(savePath?fd_name)
????????joblib.dump(fd?fd_path)
????????i?+=?1
????print?“Test?features?are?extracted?and?saved.“
#變成灰度圖片
def?rgb2gray(im):
????gray?=?im[:?:?0]*0.2989+im[:?:?1]*0.5870+im[:?:?2]*0.1140
????return?gray
#獲得圖片名稱與對應的類別
def?get_name_label(file_path):
????name_list?=?[]
????label_list?=?[]
????with?open(file_path)?as?f:
????????for?line?in?f.readlines():
????????????name_list.append(line.split(‘?‘)[0])
????????????label_list.append(line.split(‘?‘)[1])
????return?name_listlabel_list
#提取特征
def?extra_feat():
????train_nametrain_label?=?get_name_label(train_label_path)
????test_nametest_label?=?get_name_label(test_label_path)
????train_image?=?get_image_list(train_image_pathtrain_name)
????test_image?=?get_image_list(test_image_pathtest_name)
????get_feat(train_imagetrain_nametrain_labeltrain_feat_pathsize)
????get_feat(tes
- 上一篇:python編寫的類似QQ的聊天工具
- 下一篇:基于python的小型搜索引擎
評論
共有 條評論