How to convert your image to a current size in iOS

In machine learning, if you need to use .mlmodel to process your images, you will inevitably encounter a very important problem.

$0

First things first, all the .mlmodels have the Model Evaluation Parameters, for this one,it asks for the current type of the image (Color 299 x 299).

QQ20180716-155340@2x.png

$1

We can code this first to use the function.

1
guard let pixelBuffer = resizedImage.toPixelBuffer() else { return }

And brianadvent created q simple function to convert an UIImage to CVPixelBuffer for the use with Core ML. Click to Dowload

But it’s different from our needs, so let’s do some changes.

_$0

1
2
3
4
5
import CoreVideo
struct ImageProcessor {
static func pixelBuffer (forImage image:CGImage) -> CVPixelBuffer? {
...

brianadvent used the CroeVideo, and defined a stucture named ImageProcessor,

we only need to make few changes:

1
2
3
4
5
6
7
import UIKit
extension UIImage {
func toPixelBuffer() -> CVPixelBuffer? {
guard let image = self.cgImage else { return nil }
...

The rest of codes do not require any changes.And you can use this file to convert your image correctly.

UIImageToCVPixelBuffer.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import UIKit
extension UIImage {
func toPixelBuffer() -> CVPixelBuffer? {
guard let image = self.cgImage else { return nil }
let frameSize = CGSize(width: image.width, height: image.height)
var pixelBuffer: CVPixelBuffer? = nil
let status = CVPixelBufferCreate(kCFAllocatorDefault,
Int(frameSize.width),
Int(frameSize.height),
kCVPixelFormatType_32BGRA , nil, &pixelBuffer)
if status != kCVReturnSuccess { return nil }
CVPixelBufferLockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags.init(rawValue: 0))
let data = CVPixelBufferGetBaseAddress(pixelBuffer!)
let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue)
let context = CGContext(data: data, width: Int(frameSize.width), height: Int(frameSize.height), bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer!), space: rgbColorSpace, bitmapInfo: bitmapInfo.rawValue)
context?.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))
CVPixelBufferUnlockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0))
return pixelBuffer
}
}

Title: How to convert your image to a current size in iOS

Author: Tuski

Published: 07/16/2018 - 15:40:37

Updated: 07/16/2018 - 18:03:55

Link: http://www.perphet.com/2018/07/How-to-convert-your-image-to-a-current-size-in-iOS/

Protocol: Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0) Reprinted please keep the original link and author

Thx F Sup