【问题标题】:camera view does not appear in a swift/objective-c++ (opencv) project - ios 10.3 xcode 8相机视图未出现在 swift/objective-c++ (opencv) 项目中 - ios 10.3 xcode 8
【发布时间】:2017-11-21 14:25:43
【问题描述】:

我想将 OpenCV 与 swift/objective c++ 链接,以便能够为 ios 开发应用程序。我发现 CocoaPods 可以很好地与 OpenCV pod 配合使用。所以我以它们为起点,成功地尝试了一些图像拼接示例。但是,当我尝试从相机捕获图像时,我无法在显示器上看到输出。代码围绕captureOutput 函数运行和循环,但不显示相机图像。好像代码在后台运行:

目标c++代码:

@interface VideoSource () <AVCaptureVideoDataOutputSampleBufferDelegate>
  @property (strong, nonatomic) AVCaptureVideoPreviewLayer *previewLayer;
  @property (strong, nonatomic) AVCaptureSession *captureSession;
@end

@implementation VideoSource

- (void)setTargetView:(UIView *)targetView {
   if (self.previewLayer == nil) {
       return;
   }
   self.previewLayer.contentsGravity = kCAGravityResizeAspectFill;
   self.previewLayer.frame = targetView.bounds;
   self.previewLayer.affineTransform = CGAffineTransformMakeRotation(M_PI / 2);
   [targetView.layer addSublayer:self.previewLayer];
   std::cout<<"VideoSource setTargetView ... done "<<std::endl;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
       _captureSession = [[AVCaptureSession alloc] init];
       _captureSession.sessionPreset = AVCaptureSessionPreset640x480;

       AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
       NSError *error = nil;
       AVCaptureDeviceInput *input = [[AVCaptureDeviceInput alloc] initWithDevice:device error:&error];
       [_captureSession addInput:input];

       AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
       output.videoSettings = @{(NSString *)kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_32BGRA)};
       output.alwaysDiscardsLateVideoFrames = YES;
       [_captureSession addOutput:output];

       dispatch_queue_t queue = dispatch_queue_create("VideoQueue", DISPATCH_QUEUE_SERIAL);
       [output setSampleBufferDelegate:self queue:queue];

       _previewLayer = [AVCaptureVideoPreviewLayer layer];

       std::cout<<"VideoSource init ... done "<<std::endl;

    }

    return self;
}


- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
CVPixelBufferLockBaseAddress(imageBuffer, 0);

  uint8_t *base;
  int width, height, bytesPerRow;
  base = (uint8_t*)CVPixelBufferGetBaseAddress(imageBuffer);
  width = (int)CVPixelBufferGetWidth(imageBuffer);
  height = (int)CVPixelBufferGetHeight(imageBuffer);
  bytesPerRow = (int)CVPixelBufferGetBytesPerRow(imageBuffer);

  Mat mat = Mat(height, width, CV_8UC4, base);

  //Processing here
  [self.delegate processFrame:mat];

  CGImageRef imageRef = [self CGImageFromCVMat:mat];
  dispatch_sync(dispatch_get_main_queue(), ^{
     self.previewLayer.contents = (__bridge id)imageRef;
  });

  CGImageRelease(imageRef);
  CVPixelBufferUnlockBaseAddress( imageBuffer, 0 );

  std::cout<<"VideoSource captureOutput ... done "<<std::endl;
}

- (void)start {
   [self.captureSession startRunning];
   std::cout<<"VideoSource start ... done "<<std::endl;
}




- (CGImageRef)CGImageFromCVMat:(Mat)cvMat {
   if (cvMat.elemSize() == 4) {
   cv::cvtColor(cvMat, cvMat, COLOR_BGRA2RGBA);
}
  NSData *data = [NSData dataWithBytes:cvMat.data length:cvMat.elemSize()*cvMat.total()];
  CGColorSpaceRef colorSpace;

  if (cvMat.elemSize() == 1) {
      colorSpace = CGColorSpaceCreateDeviceGray();
  } else {
      colorSpace = CGColorSpaceCreateDeviceRGB();
  }

  CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);

  // Creating CGImage from cv::Mat
  CGImageRef imageRef = CGImageCreate(cvMat.cols,                                 
  //width
                                    cvMat.rows,                                 
  //height
                                    8,                                          
  //bits per component
                                    8 * cvMat.elemSize(),                       
  //bits per pixel
                                    cvMat.step[0],                            
  //bytesPerRow
                                    colorSpace,                                 
  //colorspace

  kCGImageAlphaNone|kCGBitmapByteOrderDefault,// bitmap info
                                    provider,                                   
  //CGDataProviderRef
                                    NULL,                                       
  //decode
                                    false,                                      
  //should interpolate
                                    kCGRenderingIntentDefault                   
 //intent
                                    );

  CGDataProviderRelease(provider);
  CGColorSpaceRelease(colorSpace);
  //std::cout<<"VideoSource CGImageFromCVMat ... done "<<std::endl;

  return imageRef;
}

@end

迅速的一面:

    @IBOutlet var spinner:UIActivityIndicatorView!
@IBOutlet weak var previewView: UIView!
let wrapper = Wrapper()

然后在调用函数中:

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.view.backgroundColor = UIColor.darkGray
self.wrapper.setTargetView(self.previewView)
self.wrapper.start()
}

【问题讨论】:

  • 只是要指出,上面的代码大部分来自我在这里找到的源代码:github.com/akira108/MinimumOpenCVLiveCamera 这个例子是基于以前版本的 ios/xcode,我猜这是原因之一它与 ios 10.2 /xcode 8 的版本不直接兼容。
  • 由于我设法在 ios 10.2/xcode 8 下构建和安装它,我不确定需要更改/添加什么。
  • 这是一个使用 openCV/Swift/Objective-C++ 进行图像拼接的示例,在 ios 10.2/xcode8 和 cocoapods(移植 OpenCV 3.2)下运行良好:github.com/foundry/OpenCVSwiftStitch
  • 我已经用 OpenCV 3.2 和 OpenCV 2.4.12.3 尝试了上面的源代码。两者都通过 cocoapods 移植。结果是一样的,但我在应用程序显示窗口中看不到相机视图。我还发现处理 OpenCV 2.4.12.3 更容易。我现在可以在 swift viewcontroller 中包含一个 CvVideoCameraDelegate,类似于这篇文章的建议:stackoverflow.com/questions/37413951/… 但是,即使按照 CvVideoCameraDelegate,我也看不到相机输出。

标签: ios swift xcode opencv objective-c++


【解决方案1】:

我解决了这个问题。解决方案只是通过拖动特定的 UI 组件将 UI(main.storyboard)连接到 ViewController.swift。

两种范式都有效:

  1. 上面贴的源代码改编自:https://github.com/akira108/MinimumOpenCVLiveCamera 这需要将main.storyboardUIView连接到ViewController.swift中的previewView(UIView)(只需拖放即可创建连接)

  2. 在 swift Viewcontroller (Video processing with OpenCV in IOS Swift project) 中涉及 CvVideoCameraDelegate 类。在这里,我在main.storyboard 处插入了一个UIImage 对象,并将该对象连接到ViewController 处的previewImage。因为这个例子需要在 swift (cap_ios.h) 中使用特定的 opencv 标头,所以我只使用 OpenCV 2.4 进行了测试。

【讨论】:

    猜你喜欢
    • 2023-04-10
    • 1970-01-01
    • 2018-02-03
    • 2017-09-09
    • 2017-03-08
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多