Last active
December 7, 2017 12:13
-
-
Save josete89/fc6f648a8ea9e927d23cc1196a544ecc to your computer and use it in GitHub Desktop.
Crashing with MLMultiArray
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
func resize(to: CGFloat) -> UIImage { | |
let scale = to / self.size.width | |
let newHeight = self.size.height * scale | |
UIGraphicsBeginImageContext(CGSize(width: to, height: newHeight)) | |
self.draw(in: CGRect(x: 0, y: 0, width: to, height: newHeight)) | |
let newImage = UIGraphicsGetImageFromCurrentImageContext() | |
UIGraphicsEndImageContext() | |
return newImage! | |
} | |
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 | |
} | |
func preprocess(image: UIImage) -> MLMultiArray? { | |
guard let pixels = image.resize(to: 224) | |
.pixelData()? | |
.map({ (Double($0) / 255.0 - 0.5) * 2 }) else { | |
return nil | |
} | |
guard let array = try? MLMultiArray(shape: [3, 224, 224], dataType: .double) else { | |
return nil | |
} | |
let r = pixels.enumerated().filter { $0.offset % 4 == 0 }.map { $0.element } | |
let g = pixels.enumerated().filter { $0.offset % 4 == 1 }.map { $0.element } | |
let b = pixels.enumerated().filter { $0.offset % 4 == 2 }.map { $0.element } | |
let combination = r + g + b | |
for (index, element) in combination.enumerated() { | |
let number = NSNumber(value: element) | |
array[index] = number | |
} | |
return array | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome! thanks for sharing