OpenCV行人检测我们使用HOG特征提取+SVM训练,使用默认API检测,详细了解可参考:https://zhuanlan.zhihu.com/p/75705284
使用的测试原图:
OpenCV代码:
import cv2
import numpy as np
if __name__ == '__main__':
img = cv2.imread("1.jpg")
cv2.imshow("src", img)
hog = cv2.HOGDescriptor()
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
# Detect people in the image
(rects, weights) = hog.detectMultiScale(img,
winStride=(4, 4),
padding=(8, 8),
scale=1.05,
useMeanshiftGrouping=False)
for (x, y, w, h) in rects:
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)
cv2.imshow("people_detector", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
检测结果(不太理想):
接下来使用TensorFlow SSD训练好的模型ssd_mobilenet_v1_coco_2018_01_28进行测试,代码如下:
import os
import sys
import tarfile
import cv2
import tensorflow as tf
import numpy as np
from utils import label_map_util
from utils import visualization_utils as vis_util
# What model to download.
MODEL_NAME = 'ssd_mobilenet_v1_coco_2018_01_28'
#MODEL_FILE = 'D:/tensorflow/' + MODEL_NAME + '.tar.gz'
# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_FROZEN_GRAPH = MODEL_NAME + '/frozen_inference_graph.pb'
# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join('D:/tensorflow/models/research/object_detection/data', 'mscoco_label_map.pbtxt')
NUM_CLASSES = 90
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categorys = label_map_util.convert_label_map_to_categories(label_map,max_num_classes=NUM_CLASSES,use_display_name=True)
categorys_index = label_map_util.create_category_index(categorys)
with detection_graph.as_default():
with tf.Session(graph=detection_graph) as sess:
image = cv2.imread("./4.jpg")
image_np_expanded = np.expand_dims(image,axis = 0)
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
scores = detection_graph.get_tensor_by_name('detection_scores:0')
classes = detection_graph.get_tensor_by_name('detection_classes:0')
num_detections = detection_graph.get_tensor_by_name('num_detections:0')
(boxes,scores,classes,num_detections) = sess.run([boxes,scores,classes,\
num_detections],feed_dict={image_tensor:image_np_expanded})
vis_util.visualize_boxes_and_labels_on_image_array(
image,
np.squeeze(boxes),
np.squeeze(classes).astype(np.int32),
np.squeeze(scores),
categorys_index,
min_score_thresh = 0.5,
use_normalized_coordinates = True,
line_thickness = 4
)
cv2.imshow("object_detection", image)
cv2.imwrite("result.jpg",image)
cv2.waitKey(0)
cv2.destroyAllWindows()
检测结果:
对比之下,TensorFlow SSD行人检测明显好于OpenCV Hog+SVM,所以后面如果你对目标检测有兴趣,可以看看深度学习相关的,比如TensorFlow目标检测相关。TensorFlow基础与应用实战高清视频教程