C++ OpenCV findContours问题
我有下面的代码,它执行背景减法,然后使用findContours在前景对象周围绘制边界C++ OpenCV findContours问题,c++,image-processing,opencv,background-subtraction,C++,Image Processing,Opencv,Background Subtraction,我有下面的代码,它执行背景减法,然后使用findContours在前景对象周围绘制边界 // frame - Input frame from a camera. // output - Output frame to be displayed. void process(cv:: Mat &frame, cv:: Mat &output) { cv::cvtColor(frame, gray, CV_BGR2GRAY); // initialize
// frame - Input frame from a camera.
// output - Output frame to be displayed.
void process(cv:: Mat &frame, cv:: Mat &output) {
cv::cvtColor(frame, gray, CV_BGR2GRAY);
// initialize background to 1st frame
if (background.empty())
gray.convertTo(background, CV_32F);
// convert background to 8U
background.convertTo(backImage,CV_8U);
// compute difference between current image and background
cv::absdiff(backImage,gray,foreground);
// apply threshold to foreground image
cv::threshold(foreground,output,threshold,255,cv::THRESH_BINARY_INV);
// accumulate background
cv::accumulateWeighted(gray, background, learningRate, output);
// Find regions of interest
std::vector<std::vector<cv::Point> > v; // Detected foreground points
cv::findContours(output,v,CV_RETR_LIST,CV_CHAIN_APPROX_NONE);
// Sort to find the entry with the most points at the beginning.
// This is done to overcome noisy input.
std::sort(v.begin(), v.end(), DescendingCompare);
cv::Mat drawing = frame;
std::vector<std::vector<cv::Point>> contours_poly(1);
// Determine an approximate polygon for v[0] which is the largest contour
cv::approxPolyDP( cv::Mat(v[0]), contours_poly[0], 3, false );
// Draw polygonal contour
cv::Scalar color = cv::Scalar( 0,0,255 );
cv::drawContours( drawing, contours_poly, 0, color, 2, 8, std::vector<cv::Vec4i>(), 0, cv::Point() );
// Show in a window
output = drawing;
v.clear();
}
//帧-从相机输入帧。
//输出-要显示的输出帧。
无效过程(cv::材料和框架,cv::材料和输出){
cv::CVT颜色(边框、灰色、cv_bgr2灰色);
//将背景初始化为第一帧
if(background.empty())
灰色。convertTo(背景,CV_32F);
//将背景转换为8U
背景转换(背景图像,CV_8U);
//计算当前图像和背景之间的差异
cv::absdiff(背景图像、灰色、前景);
//对前景图像应用阈值
cv::threshold(前景,输出,阈值,255,cv::THRESH\u BINARY\u INV);
//积累背景
cv::累计加权(灰色、背景、学习率、输出);
//查找感兴趣的区域
std::vector v;//检测到的前景点
cv::findContours(输出、v、cv\u RETR\u列表、cv\u链\u近似值\u无);
//排序以查找开始处点数最多的条目。
//这样做是为了克服噪声输入。
排序(v.begin()、v.end()、下降比较);
cv::Mat图纸=框架;
std::矢量轮廓_poly(1);
//确定v[0]的近似多边形,它是最大的轮廓
cv::approxPolyDP(cv::Mat(v[0]),等高线为多边形[0],3,假);
//绘制多边形轮廓
cv::Scalar color=cv::Scalar(0,0255);
cv::drawContours(绘图,等高线,多边形,0,颜色,2,8,标准::向量(),0,cv::点());
//陈列
输出=绘图;
v、 清除();
}
该图像只是一个空白的白色背景,但findContours()返回的是一个包含图像4条边的轮廓。这是发现的最大轮廓,否定了我在代码中的逻辑。是否有任何方法来修复这个问题?我希望它在屏幕为空时返回空向量
此外,是否可以改进此代码以提高效率?您的背景应为黑色(0),任何要轮廓的对象应为白色(或>=1)。将其反转,这就是为什么FindContours将背景检测为轮廓而不是对象 哎呀!愚蠢的错误。。请把你的回答作为一个单独的评论,这样我可以把它标记为正确的