18
18
// [START vision_face_detection]
19
19
namespace Google \Cloud \Samples \Vision ;
20
20
21
+ // [START import_client_library]
21
22
use Google \Cloud \Vision \V1 \ImageAnnotatorClient ;
22
23
24
+ // [END import_client_library]
25
+
23
26
// $path = 'path/to/your/image.jpg'
24
27
25
- function detect_face ($ path )
28
+ function detect_face ($ path, $ outFile = null )
26
29
{
30
+ // [START get_vision_service]
27
31
$ imageAnnotator = new ImageAnnotatorClient ();
28
-
32
+ // [END get_vision_service]
33
+
34
+ // [START detect_face]
29
35
# annotate the image
30
36
$ image = file_get_contents ($ path );
31
37
$ response = $ imageAnnotator ->faceDetection ($ image );
32
38
$ faces = $ response ->getFaceAnnotations ();
39
+ // [END detect_face]
33
40
34
41
# names of likelihood from google.cloud.vision.enums
35
42
$ likelihoodName = ['UNKNOWN ' , 'VERY_UNLIKELY ' , 'UNLIKELY ' ,
@@ -55,5 +62,44 @@ function detect_face($path)
55
62
print ('Bounds: ' . join (', ' ,$ bounds ) . PHP_EOL );
56
63
print (PHP_EOL );
57
64
}
65
+
66
+ # draw box around faces
67
+ if ($ faces && $ outFile ) {
68
+ $ imageCreateFunc = [
69
+ 'png ' => 'imagecreatefrompng ' ,
70
+ 'gd ' => 'imagecreatefromgd ' ,
71
+ 'gif ' => 'imagecreatefromgif ' ,
72
+ 'jpg ' => 'imagecreatefromjpeg ' ,
73
+ 'jpeg ' => 'imagecreatefromjpeg ' ,
74
+ ];
75
+ $ imageWriteFunc = [
76
+ 'png ' => 'imagepng ' ,
77
+ 'gd ' => 'imagegd ' ,
78
+ 'gif ' => 'imagegif ' ,
79
+ 'jpg ' => 'imagejpeg ' ,
80
+ 'jpeg ' => 'imagejpeg ' ,
81
+ ];
82
+
83
+ copy ($ path , $ outFile );
84
+ $ ext = strtolower (pathinfo ($ path , PATHINFO_EXTENSION ));
85
+ if (!array_key_exists ($ ext , $ imageCreateFunc )) {
86
+ throw new \Exception ('Unsupported image extension ' );
87
+ }
88
+ $ outputImage = call_user_func ($ imageCreateFunc [$ ext ], $ outFile );
89
+ # [START highlight_image]
90
+ foreach ($ faces as $ face ) {
91
+ $ vertices = $ face ->getBoundingPoly ()->getVertices ();
92
+ if ($ vertices ) {
93
+ $ x1 = $ vertices [0 ]->getX ();
94
+ $ y1 = $ vertices [0 ]->getY ();
95
+ $ x2 = $ vertices [2 ]->getX ();
96
+ $ y2 = $ vertices [2 ]->getY ();
97
+ imagerectangle ($ outputImage , $ x1 , $ y1 , $ x2 , $ y2 , 0x00ff00 );
98
+ }
99
+ }
100
+ # [END highlight_image]
101
+ call_user_func ($ imageWriteFunc [$ ext ], $ outputImage , $ outFile );
102
+ printf ('Output image written to %s ' . PHP_EOL , $ outFile );
103
+ }
58
104
}
59
105
// [END vision_face_detection]
0 commit comments