我可以将 a 转换UIImage
为 ARGB CVPixelBuffer
,但现在我正在尝试将 a 转换UIImage
为灰度缓冲区。自从代码通过以来,我以为我已经拥有了它,但是 coreML 模型抱怨说:
“错误域 = com.apple.CoreML 代码 = 1 “图像不是 8 灰色类型,而是不受支持 (40)”
CGContext
这是我到目前为止的灰度:
public func pixelBufferGray(width: Int, height: Int) -> CVPixelBuffer? {
var pixelBuffer : CVPixelBuffer?
let attributes = [kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue, kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue]
let status = CVPixelBufferCreate(kCFAllocatorDefault, Int(width), Int(height), kCVPixelFormatType_8IndexedGray_WhiteIsZero, attributes as CFDictionary, &pixelBuffer)
guard status == kCVReturnSuccess, let imageBuffer = pixelBuffer else {
return nil
}
CVPixelBufferLockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: 0))
let imageData = CVPixelBufferGetBaseAddress(imageBuffer)
guard let context = CGContext(data: imageData, width: Int(width), height:Int(height),
bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(imageBuffer),
space: CGColorSpaceCreateDeviceGray(),
bitmapInfo: CGImageAlphaInfo.none.rawValue) else {
return nil
}
context.translateBy(x: 0, y: CGFloat(height))
context.scaleBy(x: 1, y: -1)
UIGraphicsPushContext(context)
self.draw(in: CGRect(x:0, y:0, width: width, height: height) )
UIGraphicsPopContext()
CVPixelBufferUnlockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: 0))
return imageBuffer
}
任何帮助将不胜感激