2016-05-18 2 views
0

У меня возникло несколько проблем, на которые я нашел ответы, но ни один из них не работает для меня.Захват изображения с помощью openCV без обнаружения изображения iOS

Цель: после 60 секунд попытки обнаружить 3 QR-кода предоставить возможность вручную захватить изображение и отправить это изображение по электронной почте. Что-то вроде: прошло 60 секунд -> UIAlertController с кнопкой «ОК», что приводит к представлению захвата изображения -> Пользователь фиксирует изображение, затем изображение добавляется в качестве прикрепления к электронному письму, которое затем можно отправить

Проблема: не удается найти способ захвата изображения с использованием библиотеки OpenCV, описанной в https://www.toptal.com/machine-learning/real-time-object-detection-using-mser-in-ios

вещи, которые я пробовал:

  • Принимая скриншот во время воспроизведения видео (работает, однако я ищу для более сложного способа сделать это

    (UIImage *)capture { 
        UIGraphicsBeginImageContext(self.view.bounds.size); 
        [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; 
        UIImage *imageView = UIGraphicsGetImageFromCurrentImageContext(); 
        UIGraphicsEndImageContext(); 
        return imageView; 
    } 
    
  • Использование UIImagePickerController (Невозможно отобразить MFMailComposeViewController. Также продолжал получать «мгновенных снимков вид, что не было вынесено результаты в пустой снимок. Убедитесь, что ваше мнение было вынесено по крайней мере, один раз до мгновенных снимков или снимок после обновления экрана.»)

    (IBAction)takePhoto:(id)sender { 
        UIImagePickerController *picker = [[UIImagePickerController alloc] init]; 
        picker.allowsEditing = NO; 
        picker.modalPresentationStyle = UIModalPresentationCurrentContext; 
        picker.sourceType = UIImagePickerControllerSourceTypeCamera; 
        [self presentViewController:picker animated:YES completion:nil]; 
    } 
    
    (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { 
        UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"]; 
        [self dismissViewControllerAnimated:YES completion:nil]; 
        [self emailImage:image]; 
    } 
    
    (void)emailImage:(UIImage *)image { 
        if ([MFMailComposeViewController canSendMail]) { 
         MFMailComposeViewController *mailComposeViewController = [[MFMailComposeViewController alloc] init]; 
         mailComposeViewController.mailComposeDelegate = self; 
         mailComposeViewController.navigationBar.barStyle = UIBarStyleDefault; 
         mailComposeViewController.modalPresentationStyle = UIModalPresentationPageSheet; 
         NSString *messageBody = @""; 
         messageBody = [messageBody stringByAppendingFormat:@"Image Attached"]; 
         NSArray *recipients = [NSArray arrayWithObjects: @"[email protected]", nil]; 
         [mailComposeViewController setMessageBody:messageBody isHTML:NO]; 
         [mailComposeViewController setToRecipients:recipients]; 
    
         NSData *data = UIImagePNGRepresentation(image); 
         [mailComposeViewController addAttachmentData:data mimeType:@"image/png" fileName:@"Photo"]; 
    
         NSString *messageSubject = [NSString stringWithFormat:@"Cannot Scan"]; 
         [mailComposeViewController setSubject:messageSubject]; 
    
         [self presentViewController:mailComposeViewController animated:YES completion:nil]; 
        } 
    } 
    (void)mailComposeController:(MFMailComposeViewController*)controller 
        didFinishWithResult:(MFMailComposeResult)result 
           error:(NSError*)error { 
        NSString *msg1; 
        switch (result) 
        { 
         case MFMailComposeResultCancelled: 
          msg1 [email protected]"Sending Mail is cancelled"; 
          break; 
         case MFMailComposeResultSaved: 
          [email protected]"Sending Mail is Saved"; 
          break; 
         case MFMailComposeResultSent: 
          msg1 [email protected]"Your Mail has been sent successfully. We will be responding shortly with your results."; 
          break; 
         case MFMailComposeResultFailed: 
          msg1 [email protected]"Message sending failed"; 
          break; 
         default: 
          msg1 [email protected]"Your Mail is not Sent"; 
          break; 
        } 
        UIAlertView *mailResultAlert = [[UIAlertView alloc]initWithFrame:CGRectMake(10, 170, 300, 120)]; 
        mailResultAlert.message=msg1; 
        [email protected]"Message"; 
        [mailResultAlert addButtonWithTitle:@"OK"]; 
        [mailResultAlert show]; 
    
        dispatch_async(dispatch_get_main_queue(), ^{ 
         [self dismissViewControllerAnimated:YES completion:nil]; 
         [self dismissViewControllerAnimated:YES completion:nil]; 
        }); 
    } 
    

ли кто-нибудь знает способ просто использовать метод openCV videoCamera для захвата изображения вручную? Или как исправить UIImagePickerController? Или любые другие альтернативные решения?

Спасибо!

ответ

0

Я нашел решение для UIImagePickerController.

Через 60 секунд после обнаружения 3 QR-кодов отображается UIAlertController. Когда нажата кнопка «ОК», я выполняю переход на другой контроллер.

- (void)tooLong 
{ 
    if ([self.navigationController.visibleViewController isKindOfClass:[UIAlertController class]]) { 
     [self.navigationController.visibleViewController dismissViewControllerAnimated:YES completion:nil]; 
    } 
    [self.contourScanner stopScan]; 
    self.analysisInProgress = NO; 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Oops", nil) 
                    message:NSLocalizedString(@"It looks like we cannot detect your cup. Press 'OK' to take a photo manually. This image will be emailed to us to analyze ourselves.", nil) 
                  preferredStyle:UIAlertControllerStyleAlert]; 
     UIAlertAction *action = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { 
      [self performSegueWithIdentifier:@"takePhoto" sender:nil]; 
     }]; 
    [alert addAction:action]; 
    [self presentViewController:alert animated:YES completion:nil]; 
    }); 
} 

Затем в этом новом файле viewcontroller.m, я сделал глобальный переменный (@property (сильный, неатомический) UIImagePickerController * сборщик; ), затем я добавил следующее, чтобы правильно принять исходное изображение.

- (void)viewDidAppear:(BOOL)animated { 
[super viewDidAppear:animated]; 

    if (!self.hasPhotoCaptured) { 
     [self takePhoto]; 
    } 
} 

- (void)takePhoto { 
    self.hasPhotoCaptured = YES; 
    self.picker = [[UIImagePickerController alloc] init]; 
    self.picker.allowsEditing = NO; 
    self.picker.modalPresentationStyle = UIModalPresentationCurrentContext; 
    self.picker.sourceType = UIImagePickerControllerSourceTypeCamera; 
    self.picker.delegate = self; 
    self.picker.cameraFlashMode = UIImagePickerControllerCameraFlashModeOff; 
    self.picker.cameraDevice = UIImagePickerControllerCameraDeviceRear; 

    [self presentViewController:self.picker animated:YES completion:nil]; 
} 

Моя первоначальная проблема заключалась в том, что я не установил self.picker.delegate = self; Когда это было добавлено, был вызван OP imagePickerController.