use*_*824 4 uiimage ios swift cvpixelbuffer coreml
我能够将其转换UIImage为ARGB CVPixelBuffer,但现在我正在尝试将其转换UIImage为灰度级缓冲区.我认为自从代码通过以来我已经拥有它,但coreML模型抱怨说:
"Error Domain = com.apple.CoreML Code = 1"图像不是预期的类型8-Gray,而是Unsupported(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
}
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激
即使图像称为灰度,正确的像素格式为: kCVPixelFormatType_OneComponent8
希望这个完整的代码片段可以帮助某些人:
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_OneComponent8, 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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1693 次 |
| 最近记录: |