转:http://www.mamicode.com/info-detail-2104759.html
0.引言
自己在下载dlib官网给的example代码时,一开始不知道怎么使用,在一番摸索之后弄明白怎么使用了;
现分享下 face_detector.py和 face_landmark_detection.py这两个py的使用方法;
1.开发环境
python: 3.6.3
dlib: 19.7
2.py文件功能介绍
face_detector.py: 识别出图片文件中一张或多张人脸,并用矩形框框出标识出人脸;
face_landmark_detection.py
: 在face_detector.py的识别人脸基础上,识别出人脸部的具体特征部位:下巴轮廓、眉毛、眼睛、嘴巴,同样用标记标识出面部特征;
2.1. face_detector.py
官网给的face_detector.py
1 #!/usr/bin/python
2 #The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt
3 #4 #This example program shows how to find frontal human faces in an image. In
5 #particular, it shows how you can take a list of images from the command
6 #line and display each on the screen with red boxes overlaid on each human
7 #face.
8 #9 #The examples/faces folder contains some jpg images of people. You can run
10 #this program on them and see the detections by executing the
11 #following command:
12 #./face_detector.py ../examples/facesshape_predictor_68_face_landmarks.dat")11
12 #使用dlib的图片窗口
13 win =dlib.image_window()14
15 #1.读取图片test2.jpg的路径, ******修改此处*****
16 img = io.imread("F:/codetest2.jpg")17
18 #2.或者还是利用cmd参数输入读取路径:
19 #img=io.imread(sys.argv[1])
20
21 win.clear_overlay()22 win.set_image(img)23
24 dets = detector(img, 1)25 print("Number of faces detected: {}".format(len(dets)))26
27 for k, d inenumerate(dets):28 print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(29 k, d.left(), d.top(), d.right(), d.bottom()))30 #Get the landmarks/parts for the face in box d.
31 shape =predictor(img, d)32 print("Part 0: {}, Part 1: {} ...".format(shape.part(0),33 shape.part(1)))34 #Draw the face landmarks on the screen.
35 win.add_overlay(shape)36
37 win.add_overlay(dets)38 dlib.hit_enter_to_continue()
结果:
cmd输出:
可以看到Number of faces
detected:1,即检测到人脸数为1
1 F:\code\python\test2017110601\python_examples\face_test>python face_landmark_detection.py2 Number of faces detected: 1
3 Detection 0: Left: 200 Top: 142 Right: 468 Bottom: 409
4 Part 0: (195, 233), Part 1: (197, 267) ...5 Hit enter to continue
图片窗口结果:
对于多张人脸的检测结果:
* 关于sys.argv[]的使用:
(
如果对于代码中 sys.argv[] 的使用不了解可以参考这里 )
用来获取cmd命令行参数,例如 获取cmd命令输入“python
test.py XXXXX” 的XXXXX参数,可以用于cmd下读取用户输入的文件路径;
如果不明白可以在python代码内直接 img =
imread("F:test.jpg") 代替 img = imread(sys.argv[1])
读取图片;
用代码实例来帮助理解:
1. (sys.argv[0],指的是代码文件本身在的路径)
test1.py:
1 importsys2 a=sys.argv[0]3 print(a)
cmd input:
python test1.py
cmd output:
test1.py
2. (sys.argv[1],cmd输入获取的参数字符串中,第一个字符)
test2.py:
1 importsys2 a=sys.argv[1]3 print(a)
cmd input:
python test2.py what is your name
cmd output:
what
3. (sys.argv[1:],cmd输入获取的参数字符串中,从第一个字符开始到结束)
test3.py:
1 importsys2 a=sys.argv[1:]3 print(a)
cmd input:
python test3.py what is your name
cmd output:
[“what”,“is”,“your”,“name”]
3.(sys.argv[2],cmd输入获取的参数字符串中,第二个字符)
test4.py:
1 importsys2 a=sys.argv[2]3 print(a)
cmd input:
python test4.py what is your name
cmd output:
"is"