6

OpenCVを使用してフレームを処理するカメラからのキャプチャセッションを設定し、フレームから生成されたUIImageを使用してUIImageViewのimageプロパティを設定するコードがあります。アプリが起動すると、画像ビューの画像はnilになり、スタック上の別のView Controllerを押してからポップするまで、フレームは表示されません。その後、もう一度行うまで画像は同じままです。NSLogステートメントは、コールバックがほぼ正しいフレームレートで呼び出されることを示しています。なぜ表示されないのか、何か考えはありますか?フレームレートを1秒あたり2フレームに減らしました。処理速度が十分ではありませんか?

コードは次のとおりです。

- (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];
}
4

3 に答える 3

6

これはスレッド化に関連している可能性があります—試してみてください:

[self.delegate performSelectorOnMainThread:@selector(cameraCaptureGotFrame:) withObject:image waitUntilDone:NO];
于 2010-08-30T17:50:37.980 に答える
3

これはスレッドの問題のようです。メインスレッド以外のスレッドでビューを更新することはできません。セットアップでは、これは適切ですが、デリゲート関数captureOutput:didOutputSampleBuffer:がセカンダリスレッドで呼び出されます。そのため、そこから画像ビューを設定することはできません。Art Gillespieの答えは、不正アクセスエラーを取り除くことができればそれを解決する1つの方法です。

もう1つの方法は、captureOutput:didOutputSampleBuffer:のサンプルバッファーを変更することです。これは、キャプチャセッションにAVCaptureVideoPreviewLayerインスタンスを追加することで表示されます。何かを強調表示するなど、画像のごく一部のみを変更する場合は、これが確かに推奨される方法です。

ところで:作成した画像をセカンダリスレッドに保持しないため、アクセス不良エラーが発生する可能性があります。そのため、メインスレッドでcameraCaptureGotFrameが呼び出される前に画像が解放されます。

更新:画像を適切に保持するには、captureOutput:didOutputSampleBuffer:(セカンダリスレッド)で参照カウントを増やし、cameraCaptureGotFrame :(メインスレッド)でデクリメントします。

// 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];
}

参照カウントをインクリメントしない場合、メインスレッドでcameraCaptureGotFrame:が呼び出される前に、2番目のスレッドの自動解放プールによって画像が解放されます。メインスレッドでデクリメントしないと、イメージが解放されることはなく、数秒以内にメモリが不足します。

于 2010-10-02T18:29:19.773 に答える
0

新しい画像プロパティが更新されるたびに、UIImageViewでsetNeedsDisplayを実行していますか?

編集:

画像ビューの背景画像プロパティをいつどこで更新しますか?

于 2010-08-30T17:35:12.810 に答える