iOS Vision VNImageRequestHandler 方向问题

10

我正在尝试使用VNImageRequestHandler(iOS Vision)通过摄像头检测人脸。 当我在横屏模式下用相机对准照片时,它可以检测到人脸,但是方向相反。

  let detectFaceRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:])

enter image description here

3个回答

6

您是否尝试使用VNImageRequestHandlerorientation属性进行操作?

let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: .right, options: [:])

在使用后置摄像头进行纵向模式视频输入时,我必须将其设置为.right


1
将图像转换为CIImage,并像下面这样应用方向属性,然后将其传递给图像请求处理程序。
let orientation = CGImagePropertyOrientation(uiImage.imageOrientation)
   let imageElement = ciImage.applyingOrientation(Int32(orientation.rawValue))

        // Show the image in the UI.
        originalImage.image = uiImage

同时也请查看https://github.com/gunapandianraj/iOS-Vision的代码,用于将Vision矩形转换为UIKit矩形


尝试使用上述代码进行工作时,我在第一行尝试声明变量orientation时会得到未解决的标识符'uiImage'的错误提示。是否需要导入特定的库才能使其正常工作? - Veejay
抱歉命名规范不太好。uiImage是UIImage类型的本地变量,将被赋值为从照片库中选择的图像、拍摄的照片或下载的图像。 - Guna pandian
什么是imageElement?它在哪里被使用? - Roberto Ferraz

1
我经常会发现我的点(边界框)在垂直方向上翻转了。我使用帮助方法完全解决了这个问题:
private static func translateVisionToNormalBoundingBox(bb: CGRect, imageFullRect: CGRect) -> CGRect
{
    let renormalized = VNImageRectForNormalizedRect(bb, Int(imageFullRect.width), Int(imageFullRect.height))
    // Vertically translate origin !!!
    // Vertically translate origin !!!
    // Vertically translate origin !!!
    return CGRect(
        origin: CGPoint(
            x: renormalized.origin.x,
            y: imageFullRect.maxY - renormalized.origin.y - renormalized.size.height
        ),
        size: renormalized.size
    )
}

对于cgImage方向,我使用了StackOverflow的扩展:

extension UIImage {

var cgImagePropertyOrientation: CGImagePropertyOrientation {
    switch imageOrientation
    {
    case .down: return .down
    case .left: return .left
    case .right: return .right
    case .up: return .up
    case .downMirrored: return .downMirrored
    case .leftMirrored: return .leftMirrored
    case .rightMirrored: return .rightMirrored
    case .upMirrored: return .upMirrored
        
        // TWEAK FOR NEW CASES !!!
        // TWEAK FOR NEW CASES !!!
        // TWEAK FOR NEW CASES !!!
    @unknown default:
        return .down
    }
}

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接