有没有更简单的方法为CoreML设置像素缓冲区?

时间:2017-07-17 22:11:59

标签: swift coreml

我有一个像素缓冲区的代码,但有问题。无论出于何种原因,它要求图像为224乘224.第二个问题是CoreML不准确。必须有更准确的方法来设置像素缓冲区。

导入CoreVideo 导入UIKit 导入CoreImage

struct pixelBufferGenerator {
    static func buffer(from image: UIImage) -> CVPixelBuffer? {



        let tDictionary = [kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue, kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue] as CFDictionary
        var pixelBuffer : CVPixelBuffer?
        let status = CVPixelBufferCreate(kCFAllocatorDefault, Int(image.size.width), Int(image.size.height), kCVPixelFormatType_32ARGB, tDictionary, &pixelBuffer)
    guard (status == kCVReturnSuccess) else {
        return nil


    }

    CVPixelBufferLockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0))
    let pixelData = CVPixelBufferGetBaseAddress(pixelBuffer!)

    let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
    let context = CGContext(data: pixelData, width: Int(image.size.width), height: Int(image.size.height), bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer!), space: rgbColorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue)


    UIGraphicsPushContext(context!)
    image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
    UIGraphicsPopContext()
    CVPixelBufferUnlockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0))

        return pixelBuffer
    }
}

这个解决方案似乎有点冗长。

0 个答案:

没有答案