Created
September 15, 2017 16:09
-
-
Save gali8/6c952100083091a53934ac637c08a24a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// CoreMLExtension.swift | |
// GenderAge | |
// | |
// Created by Daniele on 12/09/17. | |
// Copyright © 2017 nexor. All rights reserved. | |
// | |
import UIKit | |
import CoreML | |
extension UIImage { | |
func pixelBuffer() -> (CVPixelBuffer?, UIImage?) { | |
let image = self | |
UIGraphicsBeginImageContextWithOptions(CGSize(width: 227, height: 227), true, 2.0) | |
image.draw(in: CGRect(x: 0, y: 0, width: 227, height: 227)) | |
let newImage = UIGraphicsGetImageFromCurrentImageContext()! | |
UIGraphicsEndImageContext() | |
let attrs = [kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue, kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue] as CFDictionary | |
var pixelBuffer : CVPixelBuffer? | |
let status = CVPixelBufferCreate(kCFAllocatorDefault, Int(newImage.size.width), Int(newImage.size.height), kCVPixelFormatType_32ARGB, attrs, &pixelBuffer) | |
guard (status == kCVReturnSuccess) else { | |
return (nil, nil) | |
} | |
CVPixelBufferLockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0)) | |
let pixelData = CVPixelBufferGetBaseAddress(pixelBuffer!) | |
let rgbColorSpace = CGColorSpaceCreateDeviceRGB() | |
let context = CGContext(data: pixelData, width: Int(newImage.size.width), height: Int(newImage.size.height), bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer!), space: rgbColorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue) | |
context?.translateBy(x: 0, y: newImage.size.height) | |
context?.scaleBy(x: 1.0, y: -1.0) | |
UIGraphicsPushContext(context!) | |
newImage.draw(in: CGRect(x: 0, y: 0, width: newImage.size.width, height: newImage.size.height)) | |
UIGraphicsPopContext() | |
CVPixelBufferUnlockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0)) | |
return (pixelBuffer, newImage) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment