9
我有下面的代碼執行背景減法,然後使用findContours圍繞前景對象繪製邊界。OpenCV 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 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();
}
的圖像僅僅是一個空白白色背景,但findContours()被返回與圖像的4個邊緣的輪廓。這最終成爲找到的最大輪廓,否定了我在代碼中的邏輯。無論如何,要解決這個問題嗎?我希望它在屏幕爲空時返回空矢量。
此外,可以在這個代碼無論如何加以改進,以提高效率?
哎呀!愚蠢的錯誤..請將您的答案作爲單獨的評論,以便我可以將其標記爲正確 – Madman