如何在Xcode中应用Deeplab V3进行实时分割?

How to apply Deeplab V3 in Xcode for real time segmentation?

其实我是swift和Deeplab V3的初学者。我真的不知道如何在 Xcode 上集成 deeplab。我只想在 ios.

中使用经过 tensorflow 训练的示例模型进行语义分割

https://github.com/cainxx/image-segmenter-ios

完成上面提到的 link,它实现了用于分段的 COREML 模型。使用标准转换工具将您的 Tensorflow 模型转换为 Coreml 模型。我们测试过一次。并且足够自信它会起作用。

Apple 在其官方网站上提供 .mlmodel 格式的 deeplab v3。你可以通过拖放轻松地将它集成到你的 xcode 中。我发现的唯一问题是输出格式是多数组,我不知道如何将结果显示为图像。 这是 deeplab mlmodel 的 link https://docs-assets.developer.apple.com/coreml/models/Image/ImageSegmentation/DeepLabV3/DeepLabV3.mlmodel

要从多数组转换为图像,您必须使用 cg 对数据进行栅格化。下面是将多数组中每个非零值的 alpha 设置为 1 的示例。因此,多阵列中识别的所有内容都具有完整的 alpha。您也可以从数组中解释不同的值。

            guard let mlMultiArray = observations.first?.featureValue.multiArrayValue else {
            
                return
            }
            let aWidth = CGFloat(mlMultiArray.shape[0].intValue)
            let aHeight = CGFloat(mlMultiArray.shape[1].intValue)

            UIGraphicsBeginImageContext(
                CGSize(width: aWidth, height: aHeight))
            if let ctx = UIGraphicsGetCurrentContext() {

                ctx.clear(CGRect(x: 0.0, y: 0.0, width: Double(aWidth), height: Double(aHeight)));

                for j in 0..<Int(aHeight) {
                    for i in 0..<Int(aWidth) {

                        let aValue =
                            (mlMultiArray[j * Int(aHeight) + i].floatValue > 0.0) ?
                                1.0 : 0.0
                        let aRect = CGRect(
                            x: CGFloat(i),
                            y: CGFloat(j),
                            width: 1.0,
                            height: 1.0)

                        let aColor: UIColor = UIColor(
                            displayP3Red: 0.0,
                            green: 0.0,
                            blue: 0.0,
                            alpha: CGFloat(aValue))

                        aColor.setFill()
                        UIRectFill(aRect)
                    }
                }
                
                let anImage = UIGraphicsGetImageFromCurrentImageContext()

                self.segmentationImage = anImage
                UIGraphicsEndImageContext()
            }