在iOS5中从CIImage创建UIImage时遇到问题

时间:2011-10-17 00:54:37

标签: iphone ios avfoundation ios5 core-image

我正在使用AVFoundation框架。在我的示例缓冲区委托中,我有以下代码:

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection{
     CVPixelBufferRef pb = CMSampleBufferGetImageBuffer(sampleBuffer);
     CIImage *ciImage = [CIImage imageWithCVPixelBuffer:pb];
     self.imageView.image = [UIImage imageWithCIImage:ciImage];
}

我能够使用CIImage来运行人脸检测器等,但它没有出现在UIImageView中...... imageView仍然是白色的。关于这个问题的任何想法? 我正在使用以下设置我的会话:

    self.session = [[AVCaptureSession alloc] init];
self.session.sessionPreset = AVCaptureSessionPreset640x480;
self.videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
self.videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:nil]; 
self.frameOutput = [[AVCaptureVideoDataOutput alloc] init];
self.frameOutput.videoSettings = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey];

4 个答案:

答案 0 :(得分:35)

这可能会有所帮助。使用此代码我遇到了同样的问题(图像没有被绘制到屏幕上):

CIImage *image = [[CIImage alloc] initWithImage:[UIImage imageNamed:@"mushroom.jpg"]];

theImageView.image = [UIImage imageWithCIImage:image];

但是,在将代码更改为此后,它现在可以正常工作:

CIImage *image = [[CIImage alloc] initWithImage:[UIImage imageNamed:@"mushroom.jpg"]];

CIContext *context = [CIContext contextWithOptions:nil];

theImageView.image = [UIImage imageWithCGImage:[context createCGImage:image fromRect:image.extent]];

要了解有关CIContext的更多信息,请查看此处: http://developer.apple.com/library/ios/#DOCUMENTATION/GraphicsImaging/Reference/QuartzCoreFramework/Classes/CIContext_Class/Reference/Reference.html#//apple_ref/occ/cl/CIContext

答案 1 :(得分:7)

这是我开始工作的一种方式:

CIContext *context = [CIContext contextWithOptions:nil];
CGImageRef ref = [context createCGImage:result fromRect:ciImage.extent];
self.imgView.image = [UIImage imageWithCGImage:ref scale:1.0 orientation:UIImageOrientationRight];
CGImageRelease(ref);

注意:多次创建上下文非常糟糕,实际上会导致内存泄漏。您应该只在类实例中创建一次属性作为属性并重复使用它!

答案 2 :(得分:3)

CIImage *ciImage = [UIImage imageNamed:@"imageName.png"].CIImage;
UIImage *uiImage = [[UIImage alloc] initWithCIImage:ciImage];

答案 3 :(得分:3)

这是我在项目中使用的完整代码示例。

- (UIImage *)makeUIImageFromCIImage:(CIImage *)ciImage {
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef cgImage = [context createCGImage:ciImage fromRect:[ciImage extent]];

    UIImage* uiImage = [UIImage imageWithCGImage:cgImage];
    CGImageRelease(cgImage);

    return uiImage;
}

CIImage基本上是图像的配方。如果您尝试直接从CIImage转换为UIImage,则会遇到问题。例如,调用

NSData * UIImageJPEGRepresentation (
   UIImage *image,
   CGFloat compressionQuality
);

将返回nil