在C ++环境下使用OpenCV绘制边界框

时间:2013-01-24 16:07:53

标签: c++ opencv bounding-box

你好peeps我已经开发了一个软件来绘制输入图像的轮廓,现在我不会把它带到一个新的水平,并在感兴趣的物体周围绘制边界框,即一个人。我查看了boundingRect()函数,但我很难理解它。也许有不同的函数算法绘制Bounding Box .....?

以下是我的程序代码:

     #include "iostream"
    #include<opencv\cv.h>
    #include<opencv\highgui.h>
    #include<opencv\ml.h>
    #include<opencv\cxcore.h>
    #include <iostream> 
    #include <string> 
    #include <opencv2/core/core.hpp> // Basic OpenCV structures (cv::Mat)
    #include <opencv2/highgui/highgui.hpp> // Video write

using namespace cv;
using namespace std;

Mat image; Mat image_gray; Mat image_gray2; Mat threshold_output;
int thresh=100, max_thresh=255;


int main(int argc, char** argv) {

    //Load Image
    image =imread("C:/Users/Tomazi/Pictures/Opencv/tomazi.bmp");

    //Convert Image to gray & blur it
    cvtColor( image, 
        image_gray, 
        CV_BGR2GRAY );

    blur( image_gray, 
        image_gray2,
        Size(3,3) );
    //Threshold Gray&Blur Image
    threshold(image_gray2, 
        threshold_output, 
        thresh, 
        max_thresh, 
        THRESH_BINARY);

    //2D Container
    vector<vector<Point>> contours;

    //Fnd Countours Points, (Imput Image, Storage, Mode1, Mode2, Offset??)
    findContours(threshold_output,
        contours, // a vector of contours
        CV_RETR_EXTERNAL,// retrieve the external contours
        CV_CHAIN_APPROX_NONE,
        Point(0, 0)); // all pixels of each contours    

    // Draw black contours on a white image
    Mat result(threshold_output.size(),CV_8U,Scalar(255));
    drawContours(result,contours,
        -1, // draw all contours
        Scalar(0), // in black
        2); // with a thickness of 2


        //Create Window
    char* DisplayWindow = "Source";
    namedWindow(DisplayWindow, CV_WINDOW_AUTOSIZE);
    imshow(DisplayWindow, result);


    waitKey(5000);
    return 1;
}

有人可以提出解决方案......?也许指导我一些资源,教程等。阅读OpenCV文档并查看boundingRect()函数我还是不明白。请帮助:))

3 个答案:

答案 0 :(得分:1)

但您也可以自己轻松计算边界框,然后使用rectangle函数绘制它们:

int maxX = 0, minX = image.cols, maxY=0, minY = image.rows;

for(int i=0; i<contours.size(); i++)
    for(int j=0; j<contours[i].size(); j++)
    {
        Point p = contours[i][j];

        maxX = max(maxX, p.x);
        minX = min(minX, p.x);

        maxY = max(maxY, p.y);
        minY = min(minY, p.y);
    }

rectangle( result, Point(minX,minY), Point(maxX, maxY), Scalar(0) );

答案 1 :(得分:1)

我在这些帖子中谈到了边界框技术:

我认为最后一个可能有助于您了解标准技术的工作原理。 OpenCV提供的是一种更简单的方法。

答案 2 :(得分:0)

This链接无效?

我认为它演示了如何获取轮廓对象并使其成为多边形近似,以及如何在其周围绘制边界矩形。

它似乎是基本的OpenCV演示之一。