Advertise Mobile SDKs Books Events Forum News Social Networking Support Us
Follow @iphonedevsdk on Twitter

Interface 2, Advanced iOS
Mockup & Code Gen
($9.99)

Make your own iPhone apps
and run them live!
(free)

Pic Frame Dynamo: Photo Editing
($0.99)

Abiliator
($1.99)

Want your application or service advertised on iPhone Dev SDK?

Go Back   iPhone Dev SDK Forum > iPhone SDK Development Forums > iPhone SDK Development > iPhone SDK Development - Advanced Discussion

Reply
 
LinkBack Thread Tools Display Modes
Old 07-12-2011, 01:58 PM   #1 (permalink)
Awesome
 
Esko2300's Avatar
 
Join Date: Jun 2009
Location: New York, N.Y.
Posts: 389
Esko2300 is on a distinguished road
Default AVFoundation question(Asked in general discussion)

Im going through the AVFoundation documentation and i cant seem to get the image to be captured and shown to me on the screen. Ive done it already but for some reason my code dident work when i got back so i started all over and now im at the same problem.

What happens is i hear the camera click after i press the button. The imageview dosent get updated, then i try to press the button again and it crashes in the method takePicture in my viewController

CameraSessionManager.h
Code:
#import <Foundation/Foundation.h>
#import <CoreVideo/CoreVideo.h>
#import <AVFoundation/AVFoundation.h>

@interface CameraSessionManager : NSObject {
    AVCaptureSession *captureSession;
    AVCaptureVideoPreviewLayer *previewLayer;
    AVCaptureVideoDataOutput *captureOutput;
}
- (id)init;
- (void)addVideoInput;
- (void)addPreviewLayer;
@property (nonatomic,retain) AVCaptureSession *captureSession;
@property (nonatomic,retain) AVCaptureVideoPreviewLayer *previewLayer;
@property (nonatomic,retain) AVCaptureVideoDataOutput *captureOutput;
@end
;

CameraSessionManager.m
Code:
#import "CameraSessionManager.h"


@implementation CameraSessionManager
@synthesize captureSession, captureOutput,previewLayer;
- (id)init{
    self = [super init];
    if(self){
        [self addVideoInput];
        [self addPreviewLayer];
    }
    return self;
}

//GOAL:Sets up the videos input
- (void)addVideoInput{
    self.captureSession = [[AVCaptureSession alloc]init];//initialize capture session
    [self.captureSession setSessionPreset:AVCaptureSessionPresetMedium];
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];//set up a capture device with Media Type Video
    if(device){
        NSError *error;
        AVCaptureDeviceInput *videoIn = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
        
        if(!error){
            if([self.captureSession canAddInput:videoIn])
                [self.captureSession addInput:videoIn];
            else
                NSLog(@"Cannot add video input");
        }
        else
            NSLog(@"Couldent create video input");
    }
    else
        NSLog(@"Couldent create video capture device");
    [self.captureSession release];
    
}
//GOAL:Sets up the preview layer
- (void)addPreviewLayer{
    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.captureSession];//initialize the preview with the capture session
    [self.previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];//set the previews layer view size
    [self.previewLayer release];
}
- (void)dealloc{
    [self.captureSession stopRunning];
    [self.captureSession release];
    [self.previewLayer release];
    [self.captureOutput release];
    [super dealloc];
}
CameraCaptureManager.h
Code:
#import <Foundation/Foundation.h>
#import "CameraSessionManager.h"

@interface CameraCaptureManager : CameraSessionManager<AVCaptureVideoDataOutputSampleBufferDelegate> {

@private
    UIImage *frame; 
    AVCaptureStillImageOutput *captureStillImage;
}
- (id)init;
- (void)addVideoOutput;
- (void)addStillImageOutput;
- (UIImage*)captureImage;
- (UIImage*)imageFromSampleBuffer:(CMSampleBufferRef)sampleBuffer;
@property (nonatomic,retain) UIImage *frame;
@property (nonatomic,retain) AVCaptureStillImageOutput *captureStillImage;
@end
CameraCaptureManager.m
Code:
#import "CameraCaptureManager.h"


@implementation CameraCaptureManager
@synthesize frame;
@synthesize captureStillImage;

- (id)init{
    self = [super init];
    if(self){
        frame = [[UIImage alloc]init];
        [self addVideoOutput];
        [self addStillImageOutput];
    }
    return self;
}

//GOAL:Sets up the videos output
- (void)addVideoOutput{
    
    self.captureOutput = [[AVCaptureVideoDataOutput alloc]init];//initialize video output
    self.captureOutput.videoSettings = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA] forKey:@"kCVPixelBufferPixelFormatTypeKey"];
    self.captureOutput.minFrameDuration = CMTimeMake(1, 15);

    if([self.captureSession canAddOutput:self.captureOutput])//check if the capture session can add the output
        [self.captureSession addOutput:self.captureOutput];//add the output to the capture session
    else 
        NSLog(@"Capture Session can't add output");
    
    dispatch_queue_t queue = dispatch_queue_create("Sample Delegate Queue", NULL);
    [self.captureOutput setSampleBufferDelegate:self queue:queue];
    dispatch_release(queue);
    
    [self.captureOutput release];
}
- (void)addStillImageOutput{
    self.captureStillImage = [[AVCaptureStillImageOutput alloc]init];
    [self.captureStillImage setOutputSettings:[NSDictionary dictionaryWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey, nil]];
    if([self.captureSession canAddOutput:self.captureStillImage])
        [self.captureSession addOutput:self.captureStillImage];
    else
        NSLog(@"Capture Session could not add still image output");
    [self.captureStillImage release];
}
- (UIImage*)captureImage{
    AVCaptureConnection *videoConnection = nil;
    
    for(AVCaptureConnection *connection in captureStillImage.connections){
        for(AVCaptureInputPort *port in connection.inputPorts){
            if([port.mediaType isEqual:AVMediaTypeVideo]){
                videoConnection = connection;
                break;
            }            
        }
        if(videoConnection){
            break;
        }
    }
    
    [self.captureStillImage captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        frame = [self imageFromSampleBuffer:imageDataSampleBuffer];
    }];
     
    return frame;
}

- (UIImage*)imageFromSampleBuffer:(CMSampleBufferRef)sampleBuffer{
    
    NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:sampleBuffer];
    UIImage *image = [UIImage imageWithData:imageData];
    return image;
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
    
}
- (void)dealloc{
    [frame release];frame = nil;
    [super dealloc];
}
;

ViewController.h
Code:
#import <UIKit/UIKit.h>
#import "CameraCaptureManager.h"
@interface CameraEdgeDetectionViewController : UIViewController {
    UIImageView *captureImageView;
    CameraCaptureManager *sessionManager;
}
- (id)init;
- (void)setUpCameraSession;
- (void)takePicture;
@property (nonatomic,retain) UIImageView *captureImageView;
@property (nonatomic,retain) CameraCaptureManager *sessionManager;
@end
ViewController.m
Code:
#import "CameraEdgeDetectionViewController.h"

@implementation CameraEdgeDetectionViewController
@synthesize sessionManager;
@synthesize captureImageView;

#pragma mark - Initializers
- (id)init{
    self = [super init];
    if(self){
        [self setUpCameraSession];
    }
    return  self;
}

#pragma mark - View lifecycle
- (void)viewDidLoad{
       [super viewDidLoad];
}
- (void)viewDidUnload{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
- (void)viewDidAppear:(BOOL)animated{
    captureImageView = [[UIImageView alloc]init];
    [captureImageView setFrame:CGRectMake(30, 30, 50, 50)];
    [self.view addSubview:captureImageView];
    
    UIButton *captureButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [captureButton setFrame:CGRectMake(30, 90, 50, 50)];
    [captureButton addTarget:self action:@selector(takePicture) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:captureButton];

    [super viewDidAppear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Camera Session
//GOAL:Sets up the camera session and adds the preview layer to the screen
- (void)setUpCameraSession{
    
    //initialize the session manager
    sessionManager = [[CameraCaptureManager alloc]init];
    
    //create Previews layer rect and position
    CGRect layerRect = self.view.layer.bounds;
    CGPoint layerPosition = CGPointMake(CGRectGetMidX(layerRect), CGRectGetMidY(layerRect));    
    
    //set the previews layer and rect
    [self.sessionManager.previewLayer setFrame:layerRect];
    [self.sessionManager.previewLayer setPosition:layerPosition];
    
    //add preview layer to views layer
    [self.view.layer addSublayer:self.sessionManager.previewLayer];
    
    //start capture session
    [self.sessionManager.captureSession startRunning];
}

//GOAL:When the user taps the button on the screen this update the imageview to the image taken
- (void)takePicture{
    [self.captureImageView setImage:[self.sessionManager captureImage]];
}

#pragma mark - Memory
- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}
- (void)dealloc{
    [self.captureImageView release];self.captureImageView = nil;
    [self.sessionManager release];self.sessionManager = nil;
    [super dealloc];
}
Esko2300 is offline   Reply With Quote
Reply

Bookmarks

Tags
avcaptureoutput, avcapturesession, avfonudation, camera

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



» Advertisements
» Online Users: 386
18 members and 368 guests
Absentia, AyClass, Diligent, dre, givensur, hussain1982, jbro, jPuzzle, momolgtm, Newbie123, Paul10, revg, sacha1996, skog, skrew88, taylor202, tomtom100
Most users ever online was 1,387, 04-10-2012 at 04:21 AM.
» Stats
Members: 175,643
Threads: 94,110
Posts: 402,858
Top Poster: BrianSlick (7,990)
Welcome to our newest member, Diligent
Powered by vBadvanced CMPS v3.1.0

All times are GMT -5. The time now is 04:44 PM.
Powered by vBulletin® Version 3.8.0
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.3.0