I have an app so far that allows the user to free draw (like a sketch pad) on a UIImageView
element.
I want to get the raw RGB pixel data (as 0
to 255
integer values) as a multidimensional array so I can feed it into a machine learning algorithm . Or is there some other way I can send the raw image data over to separate C++ function?
Is there an easy way to do this in Swift?
In Swift 3 and Swift 4, using Core Graphics, it is quite easy to do what you want:
extension UIImage {
func pixelData() -> [UInt8]? {
let size = self.size
let dataSize = size.width * size.height * 4
var pixelData = [UInt8](repeating: 0, count: Int(dataSize))
let colorSpace = CGColorSpaceCreateDeviceRGB()
let context = CGContext(data: &pixelData,
width: Int(size.width),
height: Int(size.height),
bitsPerComponent: 8,
bytesPerRow: 4 * Int(size.width),
space: colorSpace,
bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)
guard let cgImage = self.cgImage else { return nil }
context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
return pixelData
}
}