Domanda

Ho un pezzo di codice che imposta una sessione di acquisizione dalla fotocamera per elaborare i fotogrammi utilizzando OpenCV e quindi impostare la proprietà immagine di un UIImageView con un UIImage generato dal telaio. Quando inizia app, l'immagine della visualizzazione dell'immagine è pari a zero e nessun fotogramma mostrano fino a quando spingo un altro controller della vista sullo stack e poi pop fuori. Poi l'immagine rimane lo stesso fino a quando lo faccio di nuovo. dichiarazioni NSLog mostrano che il callback viene chiamata approssimativamente il frame rate corretto. Tutte le idee perché non si presenta? Ho ridotto il framerate fino a 2 fotogrammi al secondo. Non è forse elaborando abbastanza veloce?

Ecco il codice:

- (void)setupCaptureSession {
    NSError *error = nil;

    // Create the session
    AVCaptureSession *session = [[AVCaptureSession alloc] init];

    // Configure the session to produce lower resolution video frames, if your 
    // processing algorithm can cope. We'll specify medium quality for the
    // chosen device.
    session.sessionPreset = AVCaptureSessionPresetLow;

    // Find a suitable AVCaptureDevice
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    // Create a device input with the device and add it to the session.
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device 
                                                                        error:&error];
    if (!input) {
        // Handling the error appropriately.
    }
    [session addInput:input];

    // Create a VideoDataOutput and add it to the session
    AVCaptureVideoDataOutput *output = [[[AVCaptureVideoDataOutput alloc] init] autorelease];
    output.alwaysDiscardsLateVideoFrames = YES;
    [session addOutput:output];

    // Configure your output.
    dispatch_queue_t queue = dispatch_queue_create("myQueue", NULL);
    [output setSampleBufferDelegate:self queue:queue];
    dispatch_release(queue);

    // Specify the pixel format
    output.videoSettings = 
    [NSDictionary dictionaryWithObject:
     [NSNumber numberWithInt:kCVPixelFormatType_32BGRA] 
                                forKey:(id)kCVPixelBufferPixelFormatTypeKey];


    // If you wish to cap the frame rate to a known value, such as 15 fps, set 
    // minFrameDuration.
    output.minFrameDuration = CMTimeMake(1, 1);

    // Start the session running to start the flow of data
    [session startRunning];

    // Assign session to an ivar.
    [self setSession:session];
}

// Create a UIImage from sample buffer data
- (UIImage *) imageFromSampleBuffer:(CMSampleBufferRef) sampleBuffer {
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    // Lock the base address of the pixel buffer
    CVPixelBufferLockBaseAddress(imageBuffer,0);

    // Get the number of bytes per row for the pixel buffer
    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer); 
    // Get the pixel buffer width and height
    size_t width = CVPixelBufferGetWidth(imageBuffer); 
    size_t height = CVPixelBufferGetHeight(imageBuffer); 

    // Create a device-dependent RGB color space
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
    if (!colorSpace) 
     {
        NSLog(@"CGColorSpaceCreateDeviceRGB failure");
        return nil;
     }

    // Get the base address of the pixel buffer
    void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);
    // Get the data size for contiguous planes of the pixel buffer.
    size_t bufferSize = CVPixelBufferGetDataSize(imageBuffer); 

    // Create a Quartz direct-access data provider that uses data we supply
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, baseAddress, bufferSize, 
                                                              NULL);
    // Create a bitmap image from data supplied by our data provider
    CGImageRef cgImage = 
    CGImageCreate(width,
                  height,
                  8,
                  32,
                  bytesPerRow,
                  colorSpace,
                  kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little,
                  provider,
                  NULL,
                  true,
                  kCGRenderingIntentDefault);
    CGDataProviderRelease(provider);
    CGColorSpaceRelease(colorSpace);

    // Create and return an image object representing the specified Quartz image
    UIImage *image = [UIImage imageWithCGImage:cgImage];
    CGImageRelease(cgImage);

    CVPixelBufferUnlockBaseAddress(imageBuffer, 0);

    return image;
}


// Delegate routine that is called when a sample buffer was written
- (void)captureOutput:(AVCaptureOutput *)captureOutput 
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer 
       fromConnection:(AVCaptureConnection *)connection {
    // Create a UIImage from the sample buffer data
    UIImage *image = [self imageFromSampleBuffer:sampleBuffer];
    [self.delegate cameraCaptureGotFrame:image];
}
È stato utile?

Soluzione

Questo potrebbe essere correlato a threading-Prova:

[self.delegate performSelectorOnMainThread:@selector(cameraCaptureGotFrame:) withObject:image waitUntilDone:NO];

Altri suggerimenti

Questo appare come un problema di threading. Non è possibile aggiornare le vostre opinioni in qualsiasi altro thread che nel thread principale. Nella configurazione, che è buono, la funzione di delegato captureOutput: didOutputSampleBuffer: è chiamato in un thread secondario. Quindi non è possibile impostare la visualizzazione di immagini da lì. La risposta di Art Gillespie è un modo di risolverlo, se si può sbarazzarsi della errore di accesso cattivo.

Un altro modo è quello di modificare il tampone in captureOutput: didOutputSampleBuffer: e hanno è dimostrato con l'aggiunta di un AVCaptureVideoPreviewLayer esempio per la sessione di cattura. Questo è certamente il modo preferito se si modifica solo una piccola parte dell'immagine come ad esempio mettendo in evidenza qualcosa.

A proposito:. Il tuo errore di accesso cattivo potrebbe derivare dal fatto che non venga conservata l'immagine creata nel thread secondario e così sarà liberato prima del cameraCaptureGotFrame è chiamato sul thread principale

Aggiorna : Per mantenere correttamente l'immagine, incrementare il riferimento conteggio nel captureOutput: didOutputSampleBuffer: (nel thread secondario) e farlo diminuire in cameraCaptureGotFrame:. (nel thread principale)

// Delegate routine that is called when a sample buffer was written
- (void)captureOutput:(AVCaptureOutput *)captureOutput 
        didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer 
        fromConnection:(AVCaptureConnection *)connection
{
    // Create a UIImage from the sample buffer data
    UIImage *image = [self imageFromSampleBuffer:sampleBuffer];

    // increment ref count
    [image retain];
    [self.delegate performSelectorOnMainThread:@selector(cameraCaptureGotFrame:)
        withObject:image waitUntilDone:NO];

}

- (void) cameraCaptureGotFrame:(UIImage*)image
{
    // whatever this function does, e.g.:
    imageView.image = image;

    // decrement ref count
    [image release];
}

Se non si incrementa il conteggio di riferimento, l'immagine viene liberato dalla piscina il rilascio automatico del secondo thread prima che il cameraCaptureGotFrame: è chiamato nel thread principale. Se non farlo diminuire nel thread principale, le immagini non sono mai liberati e si esaurisce la memoria nel giro di pochi secondi.

Stai facendo un setNeedsDisplay sul UIImageView dopo ogni nuovo aggiornamento proprietà immagine?

Modifica:

Dove e quando stai aggiornando la proprietà immagine di sfondo nella visualizzazione dell'immagine?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top