如何使用openCV算法在对象周围绘制一个矩形

1 c++ opencv object-detection

我正在使用opencv进行对象检测.我想用鼠标点击对象后围绕对象绘制一个矩形.我可以使用什么样的技术?我试过SURF但是徒劳无功.

任何帮助将不胜感激.

yos*_*sei 6

你想用什么样的图像?如果图像是一种简单的图像(例如白纸上的铅笔,普通墙上的标记),您会考虑使用以下方法吗?我认为这是非常经典的方法,但在情况有限时效果很好.

cv::Mat img = // your image.
double threshold = 128; // needs adjustment.
int n_erode_dilate = 1; // needs adjustment.

cv::Mat m = img.clone();
cv::cvtColor(m, m, CV_RGB2GRAY); // convert to glayscale image.
cv::blur(m, m, cv::Size(5,5));
cv::threshold(m, m, threshold, 255,CV_THRESH_BINARY_INV);
cv::erode(m, m, cv::Mat(),cv::Point(-1,-1),n_erode_dilate);
cv::dilate(m, m, cv::Mat(),cv::Point(-1,-1),n_erode_dilate);

std::vector< std::vector<cv::Point> > contours;
std::vector<cv::Point> points;
cv::findContours(m, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
for (size_t i=0; i<contours.size(); i++) {
    for (size_t j = 0; j < contours[i].size(); j++) {
        cv::Point p = contours[i][j];
        points.push_back(p);
    }
}
// And process the points or contours to pick up specified object.

// for example: draws rectangle on original image.
if(points.size() > 0){
    cv::Rect brect = cv::boundingRect(cv::Mat(points).reshape(2));
    cv::rectangle(img, brect.tl(), brect.br(), cv::Scalar(100, 100, 200), 2, CV_AA);
}
Run Code Online (Sandbox Code Playgroud)