将 PKDrawing 图像转换为 RGB 像素阵列 swift IOS

问题描述

我想将用户绘图转换为像素阵列,以便我可以将其输入到机器学习模型中。用户在 brew services start mongodb-community 上绘制,然后通过 PKCanvasView 提取他们的图像。我需要将 PKDrawing 转换为像素数组。我目前正在使用此代码来转换和规范化 PKDrawing

UIImage

然而,在运行代码后,我意识到 PKDrawing 的白色背景正在转换为 extension UIImage { func normalized() -> [Float32]? { guard let cgImage = self.cgImage else { return nil } let w = cgImage.width let h = cgImage.height let bytesPerPixel = 4 let bytesPerRow = bytesPerPixel * w let bitsPerComponent = 8 var rawBytes: [UInt8] = [UInt8](repeating:0,count: w * h * 4) rawBytes.withUnsafeMutableBytes { ptr in if let cgImage = self.cgImage,let context = CGContext(data: ptr.baseAddress,width: w,height: h,bitsPerComponent: bitsPerComponent,bytesPerRow : bytesPerRow,space: CGColorSpaceCreateDeviceRGB(),bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) { let rect = CGRect(x: 0,y: 0,height: h) context.draw(cgImage,in: rect) } } var normalizedBuffer: [Float32] = [Float32](repeating: 0,count: w * h * 3) for i in 0 ..< w * h { normalizedBuffer[i] = Float32(rawBytes[i * 4 + 0]) / 255.0 normalizedBuffer[w * h + i] = Float32(rawBytes[i * 4 + 1]) / 255.0 normalizedBuffer[w * h * 2 + i] = Float32(rawBytes[i * 4 + 2]) / 255.0 } return normalizedBuffer } } 值。我希望它是 float 0 的值,因为这将是正确的 RGB 值。如何修改代码以执行此操作?

P.S 我是 IOS 开发的新手。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...