python+opencv3.4.0 實(shí)現(xiàn)HOG+SVM行人檢測(cè)的示例代碼
參照opencv官網(wǎng)例程寫了一個(gè)基于python的行人檢測(cè)程序,實(shí)現(xiàn)了和自帶檢測(cè)器基本一致的檢測(cè)效果。
網(wǎng)址 :https://docs.opencv.org/3.4.0/d5/d77/train_HOG_8cpp-example.html
opencv版本:3.4.0
訓(xùn)練集和opencv官方用了同一個(gè),可以從http://pascal.inrialpes.fr/data/human/下載,在網(wǎng)頁(yè)的最下方“here(970MB處)”,用迅雷下載比較快(500kB/s)。訓(xùn)練集文件比較亂,需要仔細(xì)閱讀下載首頁(yè)的文字介紹。注意pos文件夾下的png圖片屬性,它們用opencv無法直接打開,linux系統(tǒng)下也無法顯示,需要用matlab讀取圖片->保存才行,很奇怪的操作。
代碼如下,盡可能與opencv官方例程保持一致,但省略了很多不是很關(guān)鍵的東西。訓(xùn)練一次大概需要十幾分鐘
import cv2 import numpy as np import random def load_images(dirname, amout = 9999): img_list = [] file = open(dirname) img_name = file.readline() while img_name != '': # 文件尾 img_name = dirname.rsplit(r'/', 1)[0] + r'/' + img_name.split('/', 1)[1].strip('\n') img_list.append(cv2.imread(img_name)) img_name = file.readline() amout -= 1 if amout <= 0: # 控制讀取圖片的數(shù)量 break return img_list # 從每一張沒有人的原始圖片中隨機(jī)裁出10張64*128的圖片作為負(fù)樣本 def sample_neg(full_neg_lst, neg_list, size): random.seed(1) width, height = size[1], size[0] for i in range(len(full_neg_lst)): for j in range(10): y = int(random.random() * (len(full_neg_lst[i]) - height)) x = int(random.random() * (len(full_neg_lst[i][0]) - width)) neg_list.append(full_neg_lst[i][y:y + height, x:x + width]) return neg_list # wsize: 處理圖片大小,通常64*128; 輸入圖片尺寸>= wsize def computeHOGs(img_lst, gradient_lst, wsize=(128, 64)): hog = cv2.HOGDescriptor() # hog.winSize = wsize for i in range(len(img_lst)): if img_lst[i].shape[1] >= wsize[1] and img_lst[i].shape[0] >= wsize[0]: roi = img_lst[i][(img_lst[i].shape[0] - wsize[0]) // 2: (img_lst[i].shape[0] - wsize[0]) // 2 + wsize[0], \ (img_lst[i].shape[1] - wsize[1]) // 2: (img_lst[i].shape[1] - wsize[1]) // 2 + wsize[1]] gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY) gradient_lst.append(hog.compute(gray)) # return gradient_lst def get_svm_detector(svm): sv = svm.getSupportVectors() rho, _, _ = svm.getDecisionFunction(0) sv = np.transpose(sv) return np.append(sv, [[-rho]], 0) # 主程序 # 第一步:計(jì)算HOG特征 neg_list = [] pos_list = [] gradient_lst = [] labels = [] hard_neg_list = [] svm = cv2.ml.SVM_create() pos_list = load_images(r'G:/python_project/INRIAPerson/96X160H96/Train/pos.lst') full_neg_lst = load_images(r'G:/python_project/INRIAPerson/train_64x128_H96/neg.lst') sample_neg(full_neg_lst, neg_list, [128, 64]) print(len(neg_list)) computeHOGs(pos_list, gradient_lst) [labels.append(+1) for _ in range(len(pos_list))] computeHOGs(neg_list, gradient_lst) [labels.append(-1) for _ in range(len(neg_list))] # 第二步:訓(xùn)練SVM svm.setCoef0(0) svm.setCoef0(0.0) svm.setDegree(3) criteria = (cv2.TERM_CRITERIA_MAX_ITER + cv2.TERM_CRITERIA_EPS, 1000, 1e-3) svm.setTermCriteria(criteria) svm.setGamma(0) svm.setKernel(cv2.ml.SVM_LINEAR) svm.setNu(0.5) svm.setP(0.1) # for EPSILON_SVR, epsilon in loss function? svm.setC(0.01) # From paper, soft classifier svm.setType(cv2.ml.SVM_EPS_SVR) # C_SVC # EPSILON_SVR # may be also NU_SVR # do regression task svm.train(np.array(gradient_lst), cv2.ml.ROW_SAMPLE, np.array(labels)) # 第三步:加入識(shí)別錯(cuò)誤的樣本,進(jìn)行第二輪訓(xùn)練 # 參考 http://masikkk.com/article/SVM-HOG-HardExample/ hog = cv2.HOGDescriptor() hard_neg_list.clear() hog.setSVMDetector(get_svm_detector(svm)) for i in range(len(full_neg_lst)): rects, wei = hog.detectMultiScale(full_neg_lst[i], winStride=(4, 4),padding=(8, 8), scale=1.05) for (x,y,w,h) in rects: hardExample = full_neg_lst[i][y:y+h, x:x+w] hard_neg_list.append(cv2.resize(hardExample,(64,128))) computeHOGs(hard_neg_list, gradient_lst) [labels.append(-1) for _ in range(len(hard_neg_list))] svm.train(np.array(gradient_lst), cv2.ml.ROW_SAMPLE, np.array(labels)) # 第四步:保存訓(xùn)練結(jié)果 hog.setSVMDetector(get_svm_detector(svm)) hog.save('myHogDector.bin')
以下是測(cè)試代碼:
import cv2 import numpy as np hog = cv2.HOGDescriptor() hog.load('myHogDector.bin') cap = cv2.VideoCapture(0) while True: ok, img = cap.read() rects, wei = hog.detectMultiScale(img, winStride=(4, 4),padding=(8, 8), scale=1.05) for (x, y, w, h) in rects: cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2) cv2.imshow('a', img) if cv2.waitKey(1)&0xff == 27: # esc鍵 break cv2.destroyAllWindows()
到此這篇關(guān)于python+opencv3.4.0 實(shí)現(xiàn)HOG+SVM行人檢測(cè)的示例代碼的文章就介紹到這了,更多相關(guān)opencv HOG+SVM行人檢測(cè)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python如何通過注冊(cè)表動(dòng)態(tài)管理組件
使用注冊(cè)表的主要優(yōu)勢(shì)是可以在運(yùn)行時(shí)動(dòng)態(tài)創(chuàng)建對(duì)象,從而實(shí)現(xiàn)高度可配置和可擴(kuò)展的設(shè)計(jì),這篇文章主要介紹了python如何通過注冊(cè)表動(dòng)態(tài)管理組件,需要的朋友可以參考下2024-05-05Python實(shí)現(xiàn)多并發(fā)訪問網(wǎng)站功能示例
這篇文章主要介紹了Python實(shí)現(xiàn)多并發(fā)訪問網(wǎng)站功能,結(jié)合具體實(shí)例形式分析了Python線程結(jié)合URL模塊并發(fā)訪問網(wǎng)站的相關(guān)操作技巧,需要的朋友可以參考下2017-06-06Python如何讀寫二進(jìn)制數(shù)組數(shù)據(jù)
這篇文章主要介紹了Python如何讀寫二進(jìn)制數(shù)組數(shù)據(jù),文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-08-08