Created
August 15, 2017 15:57
-
-
Save boaerosuke/373f235eb5afa0bf50019466331df8ea to your computer and use it in GitHub Desktop.
Predict Digit takes a 28x28 image and predicts the digit
This file contains hidden or 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
| -(void)predictDigit{ | |
| //unscaled image | |
| //self.imageToDetect = [[CIImage alloc]initWithImage:self.drawingCanvas.image]; | |
| //scaled image to 28x28 | |
| UIImage *scaledCanvasImage = [self imageWithImage:self.drawingCanvas.image scaledToSize:CGSizeMake(28, 28)]; | |
| self.imageToDetect = [[CIImage alloc]initWithImage:scaledCanvasImage]; | |
| MLModel *ml_model = [[[keras_mnist_cnn alloc] init] model]; | |
| VNCoreMLModel *vnc_core_ml_model = [VNCoreMLModel modelForMLModel: ml_model error:nil]; | |
| VNCoreMLRequest *request = [[VNCoreMLRequest alloc] initWithModel: vnc_core_ml_model completionHandler: (VNRequestCompletionHandler) ^(VNRequest *request, NSError *error){ | |
| NSArray *results = [request.results copy]; | |
| VNCoreMLFeatureValueObservation *res = ((VNCoreMLFeatureValueObservation *)(results[0])); | |
| NSNumber *prediction = [NSNumber numberWithFloat:0]; | |
| NSNumber *compare= [NSNumber numberWithFloat:0]; | |
| int atIndex = 0; | |
| for(int i = 0; i<[res.featureValue multiArrayValue].count; i++){ | |
| compare = [[res.featureValue multiArrayValue] objectAtIndexedSubscript:i]; | |
| if([compare floatValue] > [prediction floatValue]){ | |
| prediction = compare; | |
| atIndex = i; | |
| } | |
| } | |
| // double predictionPercentage = [[[res.featureValue multiArrayValue] objectAtIndexedSubscript:atIndex] doubleValue]; | |
| NSString *result = @""; | |
| self.resultLabel.text = [result stringByAppendingFormat: @"Digit may be: %i", atIndex]; | |
| }]; | |
| NSDictionary *options_dict = [[NSDictionary alloc] init]; | |
| NSArray *request_array = @[request]; | |
| VNImageRequestHandler *handler = [[VNImageRequestHandler alloc] initWithCIImage:self.imageToDetect options:options_dict]; | |
| dispatch_queue_t myCustomQueue; | |
| myCustomQueue = dispatch_queue_create("com.lukau.VNImageRequestHandlerQueue", NULL); | |
| self.resultLabel.text = @"Predicting..."; | |
| dispatch_sync(myCustomQueue, ^{ | |
| [handler performRequests:request_array error:nil]; | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment