训练代码
import dlib
import cv2 as cv
def Train():
options = dlib.simple_object_detector_training_options()
options.add_left_right_image_flips = True
options.C = 5
options.num_threads = 2
options.be_verbose = True
dlib.train_simple_object_detector('data.xml', 'data.svm', options)
def deteTest():
imgpath = '1.png'
image = cv.imread(imgpath)
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
detector = dlib.simple_object_detector("data.svm")
dets = detector(gray)
for (k, d) in enumerate(dets):
cv.rectangle(image, (d.left(), d.top()), (d.left() + d.width(),
d.top() + d.height()), (0, 255, 0), 1)
cv.imshow("Output", image)
cv.waitKey(0)
if __name__ == '__main__':
while True:
print('''
| 1.训练模型 | 2.查看效果 |
'''.strip())
var = int(input(">>"))
if var == 1:
Train()
if var == 2:
deteTest()
检测代码
import cv2 as cv
import numpy as np
import dlib, mss, os
window_name = 'Test'
window_size = 2
sct = mss.mss()
monitor = {
'left': 0,
'top': 0,
'width': 1920,
'height': 1080,
}
num_res_width = 1920 // 2
num_res_height = 1080 // 2
while True:
try:
# hwnds = win32gui.FindWindow('Chrome_WidgetWin_1', None)
# left, top, right, bottom = win32gui.GetWindowRect(hwnds)
img = sct.grab(monitor=monitor)
img = np.array(img)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.namedWindow(window_name, cv.WINDOW_NORMAL)
cv.resizeWindow(window_name, num_res_width, num_res_height)
detector = dlib.get_frontal_face_detector()
dets = detector(gray)
for _, d in enumerate(dets):
cv.rectangle(img, (d.left(), d.top()), (d.left() + d.width(), d.top() + d.height()), (0, 0, 255), 2)
cv.putText(img, "1", (d.left() + d.width(), d.top() + d.height()), cv.FONT_HERSHEY_SIMPLEX, 1.2, (0, 255, 0), 2)
cv.imshow(window_name, img)
k = cv.waitKey(1)
if k % 256 == 27:
cv.destroyAllWindows()
exit('已退出...')
except Exception as e:
print(e)
os._exit(0)
视频教程
评论 (0)