#include "stdafx.h"
#include
#include
#include
#include
#include
#include
using namespace cv;
using namespace std;
using namespace zbar;
int main()
{
int c_size, i, m, n;
CvBox2D rect[10];
CvPoint2D32f rectpoint[4];
vector > contours;
Mat srcimage = imread("..\\2.jpg");
Mat image;
cvtColor(srcimage, image, CV_BGR2GRAY);//获取灰度图
threshold(image, image, 170, 255, CV_THRESH_BINARY);//二值化
findContours(image, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
c_size = contours.size();
for (i = 0; i < c_size && i<10; i++)
{
int k = 0;
Mat Imgblack = Mat::zeros(image.rows, image.cols, CV_8UC1);
rect[i] = minAreaRect(Mat(contours[i]));
cvBoxPoints(rect[i], rectpoint); //获取4个顶点坐标
drawContours(Imgblack, contours,i, Scalar(128), -1); //在全黑的图上填充
double rectarea = (rect[i].size.width* rect[i].size.height);
Scalar a = sum(Imgblack);
k = a[0]/128;
double th = double(k) / rectarea;
cout << "填充面积:" << endl << k << endl ;
cout << "矩形面积:" << endl << rectarea << endl ;
cout << "比例:" << endl << th << endl ;
line(Imgblack, rectpoint[0], rectpoint[1], Scalar(255), 2); //画矩形
line(Imgblack, rectpoint[1], rectpoint[2], Scalar(255), 2);
line(Imgblack, rectpoint[2], rectpoint[3], Scalar(255), 2);
line(Imgblack, rectpoint[3], rectpoint[0], Scalar(255), 2);
char strTmp[40];
sprintf(strTmp, "Imgblack_%d", i);
imshow(strTmp, Imgblack);
}
cvWaitKey(0);
return 0;
}
第一步:读入图像。
第二步:再现并统计。
第三步:输出。