【问题标题】:Vision and CoreML – CGImagePropertyOrientation expects wrong typeVision 和 CoreML – CGImagePropertyOrientation 需要错误的类型
【发布时间】:2020-09-04 03:43:24
【问题描述】:

目前我正在使用 ARKit/CoreML/Vision 来识别图像/对象。

为此,我查看了 Apple 的示例项目 Recognizing and Labeling Arbitrary Objects

我已将 ViewController.Swift 脚本中的以下几行复制到我的项目中:

private func classifyCurrentImage() {
    // Most computer vision tasks are not rotation agnostic so it is important 
    // to pass in the orientation of the image with respect to device.
    let orientation = CGImagePropertyOrientation(UIDevice.current.orientation)
}

这里是 CGImagePropertyOrientation 类型的常量。

当我尝试将设备方向线作为参数传递时,它会出错。由于 CGImagePropertyOrientation 需要一个 UInt32 类型的值而不是 UIDeviceOrientation

编译器错误输出:

// Cannot convert value of type 'UIDeviceOrientation' to expected argument type 'UInt32'

我认为错误出在此处UIDevice.current.orientation

【问题讨论】:

    标签: swift arkit coreml apple-vision


    【解决方案1】:

    @ibnetariq 的第一个回复解决了这段代码 sn -p 中的问题。但我找到了另一个解决方案。示例项目包含 CGImagePropertyOrientation 的扩展,它解决了我的问题。

    代码片段Utitlity.swift

    import UIKit
    import ImageIO
    
    extension CGImagePropertyOrientation {
        /**
         Converts a `UIImageOrientation` to a corresponding
         `CGImagePropertyOrientation`. The cases for each
         orientation are represented by different raw values.
    
         - Tag: ConvertOrientation
         */
        init(_ orientation: UIImageOrientation) {
            switch orientation {
            case .up: self = .up
            case .upMirrored: self = .upMirrored
            case .down: self = .down
            case .downMirrored: self = .downMirrored
            case .left: self = .left
            case .leftMirrored: self = .leftMirrored
            case .right: self = .right
            case .rightMirrored: self = .rightMirrored
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      您对 UInt32 的看法是正确的,因为 UIDeviceOrientation 是一个 Int 类型的枚举。我认为将设备方向的原始值转换/转换为 UInt32 可以解决您的问题。

      试试下面的代码

      CGImagePropertyOrientation(rawValue: UInt32(UIDevice.current.orientation.rawValue))
      

      【讨论】:

      • 感谢您的回复。我已经尝试过了,它解决了这个代码 sn-p 的问题。这会导致以下 VNImageRequestHandler(未包含在代码 sn-p 中)出现必须解包方向值的问题。但是,我看到在Apple给出的示例中,他们为CGImagePropertyOrientation编写了一个扩展,它解决了我的问题。我在一个额外的答案中写了这个解决方案:-)
      猜你喜欢
      • 2019-05-10
      • 2018-01-11
      • 2019-09-10
      • 1970-01-01
      • 2021-10-24
      • 2023-04-02
      • 1970-01-01
      • 2017-09-16
      • 2012-04-16
      相关资源
      最近更新 更多