首页 > 解决方案 > iOS 对象检测横向缩放检测

问题描述

我目前正在使用对象检测尝试在实时相机预览中检测某些事物并在它们周围绘制矩形。

这在 Portraitmode 中运行良好,但是当进入横向时,我无法计算出正确缩放矩形的数学。

代码如下所示:

//
func updateGeometry() {
        //This is the size of the actual camera frame
        let bounds = rootLayer.frame

        //To make things easier to read, bufferSize is actually the Size of captureSession?.sessionPreset = .vga640x480
        let bufferSize = CGSize(640, 480)

        self.previewLayer?.frame.size = bounds.size
        
        let multiplierX = bufferSize.width / bounds.size.width > 1 ? bufferSize.width / bounds.size.width : 1
        let multiplierY = bufferSize.height / bounds.size.height > 1 ? bufferSize.height / bounds.size.height : 1

        let xScale: CGFloat = bounds.size.width < bounds.size.height ?
            (bounds.size.width / bufferSize.width) * multiplierX:
            (bounds.size.width / bufferSize.height) * multiplierX
        
        let yScale: CGFloat = bounds.size.width < bounds.size.height ?
            (bounds.size.height / bufferSize.height) * multiplierY:
            (bounds.size.height / bufferSize.width) * multiplierY
     
        // rotate the layer into screen orientation and scale and mirror
        detectionOverlay.setAffineTransform(CGAffineTransform(
                                                rotationAngle: .pi/1.0)
                                                .scaledBy(x: -xScale, y: yScale))
        // center the layer
        detectionOverlay.position = CGPoint(x: bounds.midX, y: bounds.midY)
}

在 Portaitmode 上,图像如下所示: 在此处输入图像描述

在 Landscapemode 上,它看起来像这样: 在此处输入图像描述

正如您在横向模式中看到的那样,它有一个奇怪的偏移量,我真的无法弄清楚正确的数学。

标签: iosobjectdetectionlandscape-portrait

解决方案


推荐阅读