我正在尝试使用VNDetectFaceRectanglesRequest
新Vision
API 来检测图像上的人脸。然后,我在每个检测到的人脸上绘制一个红色矩形。
但是我在将boundingBox
fromVNFaceObservation
转换为CGRect
. 看来我唯一的问题是y origin。
这是我的代码:
let request=VNDetectFaceRectanglesRequest{request, error in
var final_image=UIImage(ciImage: image)
if let results=request.results as? [VNFaceObservation]{
for face_obs in results{
UIGraphicsBeginImageContextWithOptions(final_image.size, false, 1.0)
final_image.draw(in: CGRect(x: 0, y: 0, width: final_image.size.width, height: final_image.size.height))
var rect=face_obs.boundingBox
/*/*/*/ RESULT 2 is when I uncomment this line to "flip" the y /*/*/*/
//rect.origin.y=1-rect.origin.y
let conv_rect=CGRect(x: rect.origin.x*final_image.size.width, y: rect.origin.y*final_image.size.height, width: rect.width*final_image.size.width, height: rect.height*final_image.size.height)
let c=UIGraphicsGetCurrentContext()!
c.setStrokeColor(UIColor.red.cgColor)
c.setLineWidth(0.01*final_image.size.width)
c.stroke(conv_rect)
let result=UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
final_image=result!
}
}
DispatchQueue.main.async{
self.image_view.image=final_image
}
}
let handler=VNImageRequestHandler(ciImage: image)
DispatchQueue.global(qos: .userInteractive).async{
do{
try handler.perform([request])
}catch{
print(error)
}
}
这是迄今为止的结果。
解决方案
我自己找到了一个解决方案。
let rect=face_obs.boundingBox
let x=rect.origin.x*final_image.size.width
let w=rect.width*final_image.size.width
let h=rect.height*final_image.size.height
let y=final_image.size.height*(1-rect.origin.y)-h
let conv_rect=CGRect(x: x, y: y, width: w, height: h)
但是,我将@wei-jay 的答案标记为好答案,因为它更优雅。