-
将UIImage转换成CVPixelBufferRef
/// 下面这个属性是UIImage的,你只要UIImage的对象 image.CGImage传进来就行了 /// @property(nullable, nonatomic,readonly) CGImageRef CGImage; - (CVPixelBufferRef)GetpixelBufferWithCGImage:(CGImageRef)cgimage { NSDictionary *options = @{ (NSString*)kCVPixelBufferCGImageCompatibilityKey : @YES, (NSString*)kCVPixelBufferCGBitmapContextCompatibilityKey : @YES, (NSString*)kCVPixelBufferIOSurfacePropertiesKey: [NSDictionary dictionary] }; CVPixelBufferRef pxbuffer = NULL; CGFloat frameWidth = CGImageGetWidth(cgimage); CGFloat frameHeight = CGImageGetHeight(cgimage); CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault, frameWidth, frameHeight, kCVPixelFormatType_32BGRA, (__bridge CFDictionaryRef) options, &pxbuffer); NSParameterAssert(status == kCVReturnSuccess && pxbuffer != NULL); CVPixelBufferLockBaseAddress(pxbuffer, 0); void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer); NSParameterAssert(pxdata != NULL); CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(pxdata, frameWidth, frameHeight, 8, CVPixelBufferGetBytesPerRow(pxbuffer), rgbColorSpace, (CGBitmapInfo)kCGImageAlphaNoneSkipFirst); NSParameterAssert(context); CGContextConcatCTM(context, CGAffineTransformIdentity); CGContextDrawImage(context, CGRectMake(0, 0, frameWidth, frameHeight), cgimage); CGColorSpaceRelease(rgbColorSpace); CGContextRelease(context); CVPixelBufferUnlockBaseAddress(pxbuffer, 0); return pxbuffer; }
-
裁剪图片,全部为224*224
//需要传过来的参数有:图片 image 和自定的尺寸 - (UIImage *)image:(UIImage*)image byScalingToSize:(CGSize)targetSize { //原始 iamge UIImage *sourceImage = image; //新的image 用来接收裁剪后的image 开始时为 nil UIImage *newImage = nil; UIGraphicsBeginImageContext(targetSize); CGRect thumbnailRect = CGRectZero; //裁剪后的image 的原点和 裁剪前 的 image 的 原点相同 thumbnailRect.origin = CGPointZero; //裁剪后的image 的宽和 指定的宽 相同 thumbnailRect.size.width = targetSize.width; //裁剪后的image 的长和 指定的长 相同 thumbnailRect.size.height = targetSize.height; //将原始image 在设定的 位置上绘制(裁剪) [sourceImage drawInRect:thumbnailRect]; //把裁剪好的 image 放在 新的image 上 newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage ; }
-
调用系统相机或从相册中选择照片后,得到结果
- (void)RecognizeWithImage:(UIImage *)pImage { MobileNet *mobileNet = [[MobileNet alloc]init]; //只需要调用predictionFromImage:error:这一个方法就可以得到结果了 MobileNetOutput *output = [mobileNet predictionFromImage:[[pImage ScalingToSize:CGSizeMake(224, 224)] GetpixelBuffer] error:nil]; _photoName.text = output.classLabel; //所有可能的结果 以及每种结果的可能性百分比 NSLog(@"classLabelProbs%@",output.classLabelProbs); //可能性最大的那个结果 NSLog(@"classLabel%@",output.classLabel); }
将.mlmodel导入到项目中会用到的方法
最新推荐文章于 2024-08-24 08:29:34 发布