我有一个来自tflite自定义模型(256x256双数组)的输出,想将此数据转换为UIImage。
这是我的代码:
func toByteArray<T>(_ value: T) -> [UInt8] {
var value = value
return withUnsafePointer(to: &value) {
$0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<T>.size) {
Array(UnsafeBufferPointer(start: $0, count: MemoryLayout<T>.size))
}
}
toByteArray函数获取一个值并将其转换为UInt8形式。
let pixelData = self.toByteArray(double_array)
let height = 256
let width = 256
let numComponents = 1
let numBytes = height * width * numComponents
let colorspace = CGColorSpaceCreateDeviceGray()
let rgbData = CFDataCreate(nil, pixelData, numBytes)!
let provider = CGDataProvider(data: rgbData)!
let rgbImageRef = CGImage(width: width,
height: height,
bitsPerComponent: 8,
bitsPerPixel: 8 * numComponents,
bytesPerRow: width * numComponents,
space: colorspace,
bitmapInfo: CGBitmapInfo(rawValue: 0),
provider: provider,
decode: nil,
shouldInterpolate: true,
intent: CGColorRenderingIntent.defaultIntent)!
// Do something with rgbImageRef, or for UIImage:
let outputImage = UIImage(cgImage: rgbImageRef)
然后我用以下参数创建一个CGImage并将rgbImageRef转换为UIImage。 但是,当我运行这段代码时,我得到的只是一张黑色图像,上面带有一些看起来像噪音的白色标记。