iOS приложение Video Capture замедляется при слабом освещении

У меня есть приложение для iOS, которое использует переднюю камеру телефона и настраивает AVCaptureSession для чтения входящих данных камеры. Я установил простой счетчик кадров, чтобы проверить скорость поступления данных, и, к моему удивлению, когда камера находится в условиях низкой освещенности, частота кадров (измеряемая с помощью переменной imagecount в коде) очень низкая, но как только я двигаюсь телефон в ярко освещенной области частота кадров будет почти втрое. Я хотел бы сохранить высокую частоту кадров при обработке изображений и установить переменную minFrameDuration на 30 кадров в секунду, но это не помогло. Любые идеи о том, почему это случайное поведение?

Код для создания сеанса захвата ниже:

#pragma mark Create and configure a capture session and start it running

- (void)setupCaptureSession
{

NSError *error = nil;

// Create the session
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];
NSArray *devices = [AVCaptureDevice devices];
AVCaptureDevice *frontCamera;
AVCaptureDevice *backCamera;

for (AVCaptureDevice *device in devices) {



    if ([device hasMediaType:AVMediaTypeVideo]) {

        if ([device position] == AVCaptureDevicePositionFront) {

            backCamera = device;
        }
        else {

            frontCamera = device;
        }
    }
}


//Create a device input with the device and add it to the session.
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:backCamera
                                                                    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];
[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 30 fps, set
// minFrameDuration.
output.minFrameDuration = CMTimeMake(1,30);

//Start the session running to start the flow of data

[session startRunning];

}

#pragma mark Delegate routine that is called when a sample buffer was written

- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
   fromConnection:(AVCaptureConnection *)connection
{
  //counter to track frame rate
  imagecount++;

  //display to help see speed of images being processed on ios app
  NSString *recognized = [[NSString alloc] initWithFormat:@"IMG COUNT - %d",imagecount];
  [self performSelectorOnMainThread:@selector(debuggingText:) withObject:recognized waitUntilDone:YES];

}

1 ответ

Когда света меньше, камере требуется более длительная экспозиция для получения одинакового отношения сигнал / шум в каждом пикселе. Вот почему вы можете ожидать снижения частоты кадров при слабом освещении.

Вы устанавливаете minFrameDuration на 1/30 с, чтобы предотвратить замедление кадров с длинной выдержкой. Однако вместо этого вы должны установить maxFrameDuration: ваш код как есть говорит, что частота кадров не превышает 30 кадров в секунду, но это может быть 10 кадров в секунду или 1 кадр в секунду....

Кроме того, в Документации говорится, что любые изменения этих параметров заключаются в скобки с помощью lockForConfiguration: и unlockForConfiguration:, так что, возможно, ваши изменения просто не были приняты.

Другие вопросы по тегам