我需要将收到的 VNRectangleObservation 中的 CGPoints(bottomLeft,bottomRight,topLeft,topRight)转换为另一个坐标系(例如视图在屏幕上的坐标)。
我定义了一个请求:
// Rectangle Request
let rectangleDetectionRequest = VNDetectRectanglesRequest(completionHandler: handleRectangles)
rectangleDetectionRequest.minimumSize = 0.5
rectangleDetectionRequest.maximumObservations = 1
我在委托调用中从相机获取sampleBuffer,并执行检测请求:
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {return}
var requestOptions:[VNImageOption:Any] = [:]
if let cameraIntrinsicData = CMGetAttachment(sampleBuffer, kCMSampleBufferAttachmentKey_CameraIntrinsicMatrix, nil) {
requestOptions = [.cameraIntrinsics:cameraIntrinsicData]
}
let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: CGImagePropertyOrientation(rawValue:6)!, options: requestOptions)
do {
try imageRequestHandler.perform(self.requests)
} catch {
print(error)
}
}
在completionHandler中,我收到了结果:
func handleRectangles (request:VNRequest, error:Error?) {
guard let results = request.results as? [VNRectangleObservation] else { return }
let flipTransform = CGAffineTransform(scaleX: 1, y: -1).translatedBy(x: 0, y: -self.previewView.frame.height)
let scaleTransform = CGAffineTransform.identity.scaledBy(x: self.previewView.frame.width, y: self.previewView.frame.height)
for rectangle in results {
let rectangleBounds = rectangle.boundingBox.applying(scaleTransform).applying(flipTransform)
// convertedTopLeft = conversion(rectangle.topLeft)
// convertedTopRight = conversion(rectangle.topRight)
// convertedBottomLeft = conversion(rectangle.bottomLeft)
// convertedBottomRight = conversion(rectangle.bottomRight)
}
}
这适用于 CGRect 类型的 boundingBox,但我需要转换 CGPoints 到另一个视图的坐标系统。
问题是我不知道如何从 sampleBuffer 的 CMSampleBuffer 坐标系转换到 previewView 的坐标系。谢谢!