我正在使用 iOS 11vision 框架来检测鼻子、眼睛、嘴唇等面部特征。
视觉框架为所有面部特征提供了非常准确的归一化点。现在我试图在贝塞尔路径的帮助下在右眼上画一条红线,下面是我用来绘制相同的代码。
1)addFaceLandmarksToImage()
方法是通过视觉框架仅检测右眼并获取所有归一化点。创建上下文并用于绘制直线。
2)addNewPathToImage()
方法被定义为在检测到的右眼上添加shapelayer,这样我就可以在下一个形状中裁剪它。
func addFaceLandmarksToImage(_ face: VNFaceObservation) {
UIGraphicsBeginImageContextWithOptions(image.size, false, 1.0)
let context = UIGraphicsGetCurrentContext()
image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
context?.translateBy(x: 0, y: image.size.height)
context?.scaleBy(x: 1.0, y: -1.0)
// draw the face rect
let w = face.boundingBox.size.width * image.size.width
let imgViewWidth = face.boundingBox.size.width * imageView.frame.size.width
let h = face.boundingBox.size.height * image.size.height
let imgViewHeight = face.boundingBox.size.height * imageView.frame.size.height
let x = face.boundingBox.origin.x * image.size.width
let imgViewX = face.boundingBox.origin.x * imageView.frame.size.width
let y = face.boundingBox.origin.y * image.size.height
let imgViewY = face.boundingBox.origin.y * imageView.frame.size.height
let faceRect = CGRect(x: x, y: y, width: w, height: h)
context?.saveGState()
context?.setStrokeColor(UIColor.red.cgColor)
context?.setLineWidth(5.0)
context?.addRect(faceRect)
context?.drawPath(using: .stroke)
context?.restoreGState()
// right eye
context?.saveGState()
context?.setStrokeColor(UIColor.red.cgColor)
if let landmark = face.landmarks?.rightEye {
for i in 0...landmark.pointCount - 1 {
let point = landmark.normalizedPoints[i]
if i == 0 {
eyePath.move(to: CGPoint(x: imgViewX + CGFloat(point.x) * imgViewWidth, y: imgViewY + CGFloat(point.y) * imgViewHeight))
context?.move(to: CGPoint(x: x + CGFloat(point.x) * w, y: y + CGFloat(point.y) * h))
} else {
eyePath.addLine(to: CGPoint(x: imgViewX + CGFloat(point.x) * imgViewWidth, y: imgViewY + CGFloat(point.y) * imgViewHeight))
context?.addLine(to: CGPoint(x: x + CGFloat(point.x) * w, y: y + CGFloat(point.y) * h))
addNewPathToImage(path: eyePath)
}
}
}
addNewPathToImage(path: eyePath)
eyePath.close()
context?.closePath()
context?.setLineWidth(2.0)
context?.drawPath(using: .stroke)
context?.saveGState()
let finalImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
imageView.image = finalImage
}
func addNewPathToImage(path: UIBezierPath){
shapeLayer.path = path.cgPath
shapeLayer.strokeColor = UIColor.blue.cgColor
shapeLayer.fillColor = UIColor.red.cgColor
shapeLayer.lineWidth = 1.0
imageView.layer.addSublayer(shapeLayer)
}
现在您可以看到,我可以通过 imageview 上的当前上下文准确地绘制右眼。我已经在我的上下文中应用了 translate 和 scale 属性。
但是我试图在 addNewPathToImage() 的帮助下添加的 shapeLayer 被 翻转了。我知道 UIkit 使用的是ULO(左上原点),而核心图形基于LLO(左下原点)系统。
我需要在此过程中应用什么转换才能将该 shapeLayer 准确地放置在右眼上。
注意:我已经尝试在 shapeLayer 上进行以下转换,但没有成功。
shapeLayer.setAffineTransform(CGAffineTransform(translationX: 0, y: image.size.height))
shapeLayer.setAffineTransform(CGAffineTransform(scaleX: 1, y: -1))