我正在研究手部識別系統,我是初學者。我試圖通過找到最大的輪廓(即手)來檢測手,但它在整個框架上畫一個矩形而不是手。我該如何解決它?在opencv中尋找最大的輪廓
#include "stdafx.h"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv\cv.h"
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace cv;
using namespace std;
int main()
{
VideoCapture cap("pathaka.MP4"); // open the default camera
if (!cap.isOpened()) // check if we succeeded
return -1;
Mat edges;
namedWindow("edges", 1);
int largest_area = 0;
int largest_contour_index = 0;
Rect bounding_rect;
for (;;)
{
Mat frame;
cap >> frame; // get a new frame from video
Mat dst(frame.rows, frame.cols, CV_8UC1, Scalar::all(0));
cvtColor(frame, edges, CV_BGR2GRAY);
threshold(edges, edges, 22, 44, THRESH_BINARY);
GaussianBlur(edges, edges, Size(7, 7), 1.5, 1.5);
// Canny(edges, edges, thresh, thresh*2, 3);
int erosion_type = MORPH_ELLIPSE;
int erosion_size = 0;
Mat element = getStructuringElement(erosion_type, Size(2 * erosion_size + 1, 2 * erosion_size + 1), Point(erosion_size, erosion_size));
erode(edges, edges, element);
dilate(edges, edges, element);
vector<vector<Point>>contours; //Vector for storing contour
vector<Vec4i> hierarchy;
findContours(edges, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE); // Find the contours in the image
for (int i = 0; i< contours.size(); i++) // iterate through each contour.
{
double a = contourArea(contours[i], false); // Find the area of contour
if (a>largest_area){
largest_area = a;
largest_contour_index = i; //Store the index of largest contour
bounding_rect = boundingRect(contours[i]); // Find the bounding rectangle for biggest contour
}
}
Scalar color(255, 255, 255);
drawContours(dst, contours, largest_contour_index, color, CV_FILLED, 8, hierarchy); // Draw the largest contour using previously stored index.
rectangle(frame, bounding_rect, Scalar(0, 255, 0), 1, 8, 0);
imshow("src", frame);
imshow("largest contour", dst);
if (waitKey(30) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}
嘗試繪製所有輪廓來調試此。 –
在所有檢索的輪廓中查找凸度缺陷。應該是一個有4個重大缺陷的人。 –
好的,謝謝,我會盡力調查那 – Lily