本讲实现:给定原始图片,通过直方图反投影画出目标颜色所在的所有区域中的最大区域的轮廓,并用矩形框出。
依赖的类文件见文章《Opencv直方图反投影识别颜色》
以下是实现的主程序
#include <opencv2\opencv.hpp>
#include "Histogram1D.h"//定义1维灰度直方图的获取与绘制方法类:class Histogram1D
#include "ColorHistogram.h"//定义3维彩色直方图的获取与绘制方法类:class ColorHistogram
#include "ContentFinder.h"//定义反向投影直方图检测方法的类:class ContentFinder
using namespace std;
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 == 27) break;
}
return 0;
}