1
我能够将UIImage
转换为ARGB CVPixelBuffer
,但现在我试图将UIImage
转换为灰度级缓冲区。 我想我就再没代码经历,但coreML模型笙歌说:将UIImage转换为8灰度像素缓冲区
“错误域= 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
}
任何帮助,将不胜感激
当你创建这个代码上下文,您是否尝试用kCVPixelFormatType_8IndexedGray_WhiteIsZero或kCVPixelFormatType_8Indexed替换空格参数? –
感谢您的帮助,正确的像素格式是kCVPixelFormatType_OneComponent8灰度UIImage – user1988824
你可能已经投了我的评论至少大声笑 –