首页 > 解决方案 > Vision 和 CoreML – CGImagePropertyOrientation 需要错误的类型

问题描述

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

为此,我查看了 Apple 的示例项目识别和标记任意对象

我已将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

标签: swiftarkitcoremlapple-vision

解决方案


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

代码片段实用程序.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
        }
    }
}

推荐阅读