git:https://github.com/linyi0604/Computer-Vision
1 # coding:utf-8
2
3 import cv2 4
5
6 # 檢測i方框 包含o方框
7 def is_inside(o, i): 8 ox, oy, ow, oh = o 9 ix, iy, iw, ih = i 10 return ox > ix and ox + ow < ix + iw and oy + oh < iy + ih 11
12
13 # 將人外面的方框畫出來
14 def draw_person(image, person): 15 x, y, w, h = person 16 cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 255), 2) 17
18
19 # 讀入圖片
20 img = cv2.imread("../data/people2.jpg") 21 # 獲取hog檢測器對象
22 hog = cv2.HOGDescriptor() 23 # 設置檢測人的默認檢測器
24 hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector()) 25 # 在圖片中檢測人,
26 # 返回found列表 每個元素是一個(x, y, w, h)的矩形,w是每一個矩形的置信度
27 found, w = hog.detectMultiScale(img) 28 found_filtered = [] 29 # 如果方框有包含,只留下內部的小方塊
30 for ri, r in enumerate(found): 31 for qi, q in enumerate(found): 32 if ri != qi and is_inside(r, q): 33 break
34 else: 35 found_filtered.append(r) 36
37 # 將每一個方塊畫出來
38 for person in found_filtered: 39 draw_person(img, person) 40
41
42 cv2.imshow("person detection", img) 43 cv2.waitKey() 44 cv2.destroyAllWindows()