ios - 在 iOS 中使用 imread()

标签 ios objective-c swift opencv imread

我正在尝试在 iOS 上使用 OpenCV。当我通过 Xcode 使用应用程序中包含的图像时,一切正常。

但是我需要读取通过相机拍摄的图像。我已经在 StackOverflow 和其他网站上测试了这里的大量建议,但没有成功。

我尝试过使用 OpenCV 的 UIImageToMat ,我尝试将图像保存到设备上的文档目录中,然后通过 imread() 读取该文件。

不幸的是,Mat 对象的数据为 NULL,矩阵为空。有人有什么想法吗?

let filename = getDocumentsDirectory().appendingPathComponent("temp.jpg")
try? dataImage.write(to: filename)

let test = OpenCVWrapper()
let plate = test.getLicensePlate(filename.absoluteString)
print(plate ?? "nil")

我已经检查过该文件确实存在于文档目录中,所以我真的不知道发生了什么!

最佳答案

好吧,经过几个小时的挫折后,我让它工作了。在这里为任何希望使用 iOS 版 OpenALPR 库(以及通过 imread() 扩展 OpenCV)的人发布我的解决方案。

首先,上面的代码使用了一个 URL 路径,通过 .absolutestring 方法转换为字符串。该路径不适用于 imread()。您将需要使用以下内容:

if let image = UIImage(data: dataImage)?.fixOrientation() {
    if let data = UIImageJPEGRepresentation(image, 1) {

        var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        path.append("/temp.jpg")
        try? data.write(to: URL(fileURLWithPath: path))

        let cv = OpenCVWrapper()
        plate = cv.getLicensePlate(path)
        print(plate ?? "nil")
    }
}

如果您正在执行对方向敏感的分析,则需要在处理之前修复捕获的图像方向。请参阅here以获得解释。

这是上述链接中提到的 UIImage 扩展的 Swift 3 版本:

extension UIImage {

    func CGRectMake(_ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) -> CGRect {
        return CGRect(x: x, y: y, width: width, height: height)
    }

    func fixOrientation() -> UIImage {
        if self.imageOrientation == UIImageOrientation.up {
            return self
        }

        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        self.draw(in: CGRectMake(0, 0, self.size.width, self.size.height))
        let normalizedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        return normalizedImage;
    }
}

关于ios - 在 iOS 中使用 imread(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44755087/

相关文章:

ios - 在 Mac OS 上安装 Kony

ios - NSNotificationCenter 发布 C 结构并从通知回调函数中检索它

iphone - 触摸内容 View 中的图像时防止 UITableViewCell 突出显示

ios - 按下按钮时在类中使用数据 Objective-C/iOS

ios - 动态改变 UITableViewCell 文本的 textColor

swift - 如何根据 swift 中的随机数生成来显示某个 View ?

ios - Storyboard中的 Appdelegate 变量

ios - 收不到推送通知 - ios

ios - Reactive Cocoa - 然后是自定义信号与 UI 信号

swift - 如何打开带有事件的日历 - NSURL calshow :