This is true: given the original picture, the contour of the largest area in all areas of the target color is drawn by the histogram inverse projection, and the rectangle is used.
dependent class files See the article "OpenCV histogram anti-projection recognition color"
The following is the implementation of the main program
#include <opencv2\opencv.hpp> #include "Histogram1D.h"//define the method of obtaining and drawing a 1-D gray histogram:class histogram1d #include "ColorHistogram.h"//define 3-D color histogram acquisition and rendering method class:class colorhistogram #include "
ContentFinder.h "//defines the class:class contentfinder using namespace std for the reverse projection histogram detection method;
using namespace CV;
int main () {//Read input image Cv::mat image = Cv::imread ("E:\\programproject\\1.png");
if (!image.data) return 0;
Define image ROI Cv::mat Imageroi;
Imageroi = Image (Cv::rect (0, 0, 30, 24));
Contentfinder Finder;
Cv::mat RESULT1;
Cv::mat color;
Colorhistogram HC;
Hc.setsize (4);
Cv::mat shist = Hc.gethistogram (Imageroi);
Finder.sethistogram (shist);
Finder.setthreshold (0.09f);
Videocapture Cap (1);
while (true) {cap >> color;
Namedwindow ("1");
Imshow ("1", color);
RESULT1 = Finder.find (color);
Mat Res; Mat element5 (3, 3, cv_8u, SCALar (1));
Morphologyex (RESULT1, Res, morph_close, ELEMENT5);
Blur (Res, res, Size (2, 2));
Vector<std::vector<point> >contours;
Findcontours (res, contours, cv_retr_external, cv_chain_approx_none);
unsigned __int64 cmin = 20;
vector<vector<point> >::const_iterator itc = Contours.begin ();
int cnt = 0;
int store =-1; while (ITC = Contours.end ()) {if (Itc->size () > cmin) {cmin = ITC
->size ();
store = CNT;
} itc++;
cnt++;
} if (store = =-1) {Mat Black (res.size (), cv_8u, Scalar (255));
Cv::namedwindow ("Color Detection Result");
Cv::imshow ("Color Detection Result", black);
Continue
} else {Mat result1 (res.size (), cv_8u, Scalar (255)); Drawcontours (RESULT1, contours, store, Scalar (0),2);
Vector<point> Retan = Contours[store];
Rect r0 = Boundingrect (Mat (Retan));
Rectangle (RESULT1, r0, Scalar (0), 2);
/*float radius;
POINT2F Center;
Minenclosingcircle (Mat (contours[store)), center, RADIUS);
Circle (RESULT1, point (center), static_cast<int> (RADIUS), Scalar (0), 2); *//*vector<point> Poly;
APPROXPOLYDP (Mat (Contours[store]), Poly, 5, true);
Vector<point>::const_iterator ITP = Poly.begin ();
while (ITP = (Poly.end ()-1)) {line (RESULT1, *ITP, * (ITP + 1), Scalar (0), 2);
++ITP;
} line (RESULT1, * (Poly.begin ()), * (Poly.end ()-1), Scalar (20), 2);
Vector<point> Hull;
Convexhull (Mat (Contours[store]), Hull); *//*ITC = Contours.begin (); while (ITC! = Contours.end ()) {Moments mOm = cv::moments (Mat (*itc++));
Circle (RESULT1, point (mom.m10/mom.m00, mom.m01/mom.m00), 2, Scalar (2));
}*/Cv::namedwindow ("Color Detection Result");
Cv::imshow ("Color Det ' ction Result", RESULT1);
} char C = Waitkey (33);
if (c = =) break;
} return 0; }