Amazing-Python-Scripts
200 строк · 5.5 Кб
1# *^_^* coding:utf-8 *^_^*
2"""
3SmokeDect-v0.2
4检测方法:用MOG2提取运动区域,分小块提取hog特征,用svm分类
5"""
6
7from __future__ import print_function # use print()8
9__author__ = 'stone'10__date__ = '15-11-30'11
12import cv213import numpy as np14from time import time15import os16
17DEBUG_MOD = True18vName = '/home/stone/Code/FlameSmokeDetect/medias/videos/CTC.BG.055_11_320x240.avi'19train_directory = '/home/stone/Code/FlameSmokeDetect/tools/clips'20BLOCK_SIZE = 4021
22
23def hog_feature(img):24"""25Extract HOG feature
26"""
27win_size = (16, 16)28block_size = (8, 8)29block_stride = (8, 8)30cell_size = (8, 8)31nbins = 932descriptor = cv2.HOGDescriptor(33win_size, block_size, block_stride, cell_size, nbins)34hog_feature_hog = descriptor.compute(img)35hog_feature_hog = np.float32(hog_feature_hog)36return hog_feature_hog37
38
39def svm_create():40"""41initial a SVM
42"""
43svm_params = dict(kernel_type=cv2.ml.SVM_LINEAR,44svm_type=cv2.ml.SVM_C_SVC,45C=1,46gamma=0.5)47svm = cv2.ml.SVM_create()48svm.setKernel(svm_params['kernel_type'])49svm.setType(svm_params['svm_type'])50svm.setC(svm_params['C'])51svm.setGamma(svm_params['gamma'])52return svm53
54
55def file_path(directory):56"""57generate a full directory path
58"""
59files = os.listdir(directory)60path = []61
62for name in files:63full_name = os.path.join(directory, name)64path.append(full_name)65print('%s 的文件数: %d\n' % (directory, len(path)))66return path67
68
69# def load_hog(hog_path):
70# """
71# load hog files
72# """
73# print('loading hog files...')
74# hog = []
75# for fp in hog_path:
76# content = np.loadtxt(fp)
77# hog.append(content)
78# hog = np.float32(hog)
79# # print(hog)
80# print('finished!')
81# return hog
82
83
84def split(img, cell_size, flatten=False):85"""86Split into small blocks
87"""
88split_h, split_w = img.shape[:2]89sx, sy = cell_size90split_cells = [np.hsplit(row, split_w // sx)91for row in np.vsplit(img, split_h // sy)]92split_cells = np.array(split_cells)93if flatten:94split_cells = split_cells.reshape(-1, sy, sx)95return split_cells96
97
98if __name__ == '__main__':99print(__doc__)100start_time = time()101count = 0102
103# create and train a SVM104train_path = file_path(train_directory)105train_hog = []106response = []107for img_path in train_path:108print(img_path.split('-')[0])109if img_path.split('-')[0] == '/home/stone/Code/FlameSmokeDetect/tools/clips/p':110response.append(1)111elif img_path.split('-')[0] == '/home/stone/Code/FlameSmokeDetect/tools/clips/n':112response.append(0)113img = cv2.imread(img_path)114train_hog.append(hog_feature(img))115print(len(train_hog[0]))116train_hog = np.float32(train_hog)117print(response)118response = np.array(response)119svm = svm_create()120svm.train(train_hog, cv2.ml.ROW_SAMPLE, response)121if svm.isTrained():122print('SVM is trained!')123
124cap = cv2.VideoCapture(vName)125fgbg = cv2.createBackgroundSubtractorMOG2(detectShadows=False)126
127while 1:128result = []129ret, frame = cap.read()130if frame is None:131print("The End!!!")132break133
134# if count < 500:135# count += 1136# continue137
138frame_copy = frame.copy()139frame = cv2.GaussianBlur(frame, (5, 5), 2)140frame = cv2.medianBlur(frame, 5)141
142gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)143fmask = fgbg.apply(gray_frame)144
145kernel = np.ones((20, 20), np.uint8)146fmask = cv2.medianBlur(fmask, 3)147fmask = cv2.dilate(fmask, kernel)148
149fmask_copy = fmask.copy()150
151contour_img, contours, hierarchy = cv2.findContours(152fmask_copy, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)153
154if contours is None:155continue156
157for cnt in contours:158x, y, w, h = cv2.boundingRect(cnt)159
160if w < BLOCK_SIZE or h < BLOCK_SIZE:161pass162else:163cells = split(frame, (BLOCK_SIZE, BLOCK_SIZE), flatten=False)164cells_x_1 = x / BLOCK_SIZE165cells_x_2 = (x + w) / BLOCK_SIZE166cells_y_1 = y / BLOCK_SIZE167cells_y_2 = (y + h) / BLOCK_SIZE168for candidate in cells[cells_y_1:cells_y_2, cells_x_1:cells_x_2]:169for i in xrange(candidate.shape[0]):170hog = []171hog.append(hog_feature(candidate[i]))172hog = np.float32(hog)173
174result.append(svm.predict(hog)[0])175# print('HogFeature/hog%d-%d-%d' % (count, i, j))176# hog_file = 'HogFeature/hog%d-%d-%d' % (count, i, j)177# np.savetxt(hog_file, hog)178
179if DEBUG_MOD is True:180cv2.rectangle(frame_copy, (x, y),181(x + w, y + h), (0, 255, 0), 2)182
183print(result)184if 0 in result:185print('yes')186print('frame %d' % count)187cv2.imshow('fmask', frame_copy)188frame_and = cv2.bitwise_and(frame, frame, mask=fmask)189
190count += 1191k = cv2.waitKey(100) & 0xFF192if k == 27:193break194
195end_time = time()196total_time = end_time - start_time197print('Total time: %d' % total_time)198print(count)199cap.release()200cv2.destroyAllWindows()201