如何使用openCV检测实时摄像机中的移动物体

how to detect moving object in live video camera using openCV

我正在为我的 ios 应用程序使用 openCV 来检测实时摄像机中的移动物体,但我不熟悉 openCV 的使用,请帮助我。任何其他方式也欢迎。

- (void)viewDidLoad {
    [super viewDidLoad];

    self.videoCamera.delegate = self;
    self.videoCamera = [[CvVideoCamera alloc] initWithParentView:self.view];

    self.videoCamera.defaultAVCaptureDevicePosition = AVCaptureDevicePositionBack;
    self.videoCamera.defaultAVCaptureSessionPreset = AVCaptureSessionPreset352x288;
    self.videoCamera.defaultAVCaptureVideoOrientation = AVCaptureVideoOrientationPortrait;
    self.videoCamera.defaultFPS = 30;
    self.videoCamera.grayscaleMode = NO;
    [self.videoCamera start];
//    cv::BackgroundSubtractorMOG2 bg;

}
- (void)processImage:(cv::Mat&)image
{
    //process here
    cv::cvtColor(image, img, cv::COLOR_BGRA2RGB);
    int fixedWidth = 270;
    cv::resize(img, img, cv::Size(fixedWidth,(int)((fixedWidth*1.0f)*   (image.rows/(image.cols*1.0f)))),cv::INTER_NEAREST);

    //update the model
   bg_model->operator()(img, fgmask, update_bg_model ? -1 : 0);


    GaussianBlur(fgmask, fgmask, cv::Size(7, 7), 2.5, 2.5);
    threshold(fgmask, fgmask, 10, 255, cv::THRESH_BINARY);

    image = cv::Scalar::all(0);
    img.copyTo(image, fgmask);
}

我是 openCV 的新手,所以我不知道该怎么做。

我假设您想要与此演示具有相似性质的东西:https://www.youtube.com/watch?v=UFIVCDDnrmM 这会给你运动并删除图像的背景。

任何时候您想要检测运动时,您通常必须首先确定什么在移动,什么在静止。此任务是通过拍摄几帧并比较它们以确定部分是否足够不同以被视为不在背景中来完成的。 (通常超过一定的一致性阈值。)

要查找图像中的背景,请查看:http://docs.opencv.org/master/d1/dc5/tutorial_background_subtraction.html

后记你将需要一个实现(可能是像 canny 这样的边缘检测器)来识别你想要的对象并跟踪它的运动。 (确定速度、方向等)这将特定于您的用例,并且原始问题中没有足够的信息来具体说明您在这里需要什么。

另一个非常好的资源是:http://www.intorobotics.com/how-to-detect-and-track-object-with-opencv/ 这甚至有一个专门用于将移动设备与 opencv 结合使用的部分。 (他们使用的使用场景是机器人技术,这是计算机视觉最大的应用之一,但你应该可以根据需要使用它;尽管需要进行一些修改。)

如果这对您有帮助,请告诉我,如果我可以做任何其他事情来帮助您。

将此代码添加到 processImage 委托:

- (void)processImage:(cv::Mat&)image
{
      //process here
      cv::cvtColor(image, img, cv::COLOR_BGRA2RGB);
      int fixedWidth = 270;
     cv::resize(img, img, cv::Size(fixedWidth,(int)((fixedWidth*1.0f)*   (image.rows/(image.cols*1.0f)))),cv::INTER_NEAREST);

    //update the model
    bg_model->apply(img, fgmask, update_bg_model ? -1 : 0);

    GaussianBlur(fgmask, fgmask, cv::Size(7, 7), 2.5, 2.5);
    threshold(fgmask, fgmask, 10, 255, cv::THRESH_BINARY);

    image = cv::Scalar::all(0);
    img.copyTo(image, fgmask);
}

您需要将以下声明为全局变量

cv::Mat img, fgmask;
cv::Ptr<cv::BackgroundSubtractor> bg_model;
bool update_bg_model;
Where, img <- smaller image fgmask <- the mask denotes that where motion is happening update_bg_model <- if you want to fixed your background;

Please refer this URL 了解更多信息。