title: How to convert a UIImage to a CVPixelBuffer
body: <p>Apple's new CoreML framework has a prediction function that takes a <code>CVPixelBuffer</code>. In order to classify a <code>UIImage</code> a conversion must be made between the two.</p>
  
  <p>Conversion code I got from an Apple Engineer:</p>
  
  <pre><code>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, &amp;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))
  </code></pre>
  
  <p>This solution is in swift and is for a grayscale image. Changes that must be made depending on the type of image are:</p>
  
  <ul>
  <li>Line 5 | <code>kCVPixelFormatType_OneComponent8</code> to another <code>OSType</code> (<code>kCVPixelFormatType_32ARGB</code> for RGB)</li>
  <li>Line 8 | <code>colorSpace</code> to another <code>CGColorSpace</code> (<code>CGColorSpaceCreateDeviceRGB</code> for RGB)</li>
  <li>Line 9 | <code>bitsPerComponent</code> to the number of bits per pixel of memory (32 for RGB)</li>
  <li>Line 9 | <code>bitmapInfo</code> to a nonzero <code>CGBitmapInfo</code> property (<code>kCGBitmapByteOrderDefault</code> is the default)</li>
  </ul>