Apple 的新 CoreML 框架有一个预测功能,它需要一个CVPixelBuffer
. 为了分类,UIImage
必须在两者之间进行转换。
我从 Apple 工程师那里得到的转换代码:
1 // image has been defined earlier
2
3 var pixelbuffer: CVPixelBuffer? = nil
4
5 CVPixelBufferCreate(kCFAllocatorDefault, Int(image.size.width), Int(image.size.height), kCVPixelFormatType_OneComponent8, nil, &pixelbuffer)
6 CVPixelBufferLockBaseAddress(pixelbuffer!, CVPixelBufferLockFlags(rawValue:0))
7
8 let colorspace = CGColorSpaceCreateDeviceGray()
9 let bitmapContext = CGContext(data: CVPixelBufferGetBaseAddress(pixelbuffer!), width: Int(image.size.width), height: Int(image.size.height), bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelbuffer!), space: colorspace, bitmapInfo: 0)!
10
11 bitmapContext.draw(image.cgImage!, in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
该解决方案速度很快,适用于灰度图像。必须根据图像类型进行的更改是:
- 5号线|
kCVPixelFormatType_OneComponent8
到另一个OSType
(kCVPixelFormatType_32ARGB
RGB) - 8号线|
colorSpace
到另一个CGColorSpace
(CGColorSpaceCreateDeviceRGB
RGB) - 9号线|
bitsPerComponent
到内存每个像素的位数(RGB 为 32) - 9号线|
bitmapInfo
到非零CGBitmapInfo
属性(kCGBitmapByteOrderDefault
是默认值)