Tôi có đoạn mã sau thực hiện phép trừ nền và sau đó sử dụng findContours để vẽ một đường bao quanh đối tượng nền trước.OpenCV findContours issue
// 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();
}
Hình ảnh chỉ là nền trắng trống nhưng findContours() trả về đường viền với 4 cạnh của hình ảnh. Điều này kết thúc được các đường viền lớn nhất được tìm thấy, phủ nhận logic của tôi trong code.Is có anyway để sửa lỗi này? Tôi muốn nó trả về một véc tơ rỗng khi màn hình trống.
Ngoài ra, mã này có thể được cải thiện trong anyway để nâng cao hiệu quả?
Yikes! Lỗi ngớ ngẩn .. Vui lòng trả lời dưới dạng nhận xét riêng để tôi có thể đánh dấu câu trả lời là chính xác – Madman