1.轮廓查找与绘制代码
#include
#include
#include
#include
using namespace std;
using namespace cv;
Mat src, temp;
vector> contours;
vector hierarchy;
int main()
{
src = imread("src1.png"); //待搜索图像
temp = src.clone(); //原图克隆图像
cvtColor(src, src, COLOR_BGR2GRAY);
threshold(src, src, 100, 255, THRESH_BINARY);
imshow("src", src);
//查找轮廓并绘制轮廓【查找轮廓之前要将输入凸显转化为二值图】
findContours(src, contours, hierarchy,RETR_LIST,CHAIN_APPROX_SIMPLE);
drawContours(temp, contours, -1, Scalar(0, 255, 0), 2, 8);
imshow("temp", temp);
waitKey(0);
}
2.绘制轮廓的凸包
#include
#include
#include
#include
using namespace std;
using namespace cv;
int main()
{
Mat src = imread("1.png"); //读取图像
Mat dst = src.clone(); //原图的克隆图像
cvtColor(src, src, COLOR_BGR2GRAY); //灰度化
threshold(src, src, 100, 255, THRESH_BINARY_INV);
//imshow("src", src);
vector> contours;
vector hierachy;
findContours(src, contours, hierachy, RETR_EXTERNAL, CHAIN_APPROX_NONE);
//drawContours(dst, contours, -1, Scalar(0, 255, 0), 2, 8);
//imshow("dst", dst);
//应用凸包检测
vector> hull(contours.size());
for (int i = 0; i < contours.size(); i++)
{
convexHull(contours[i], hull[i], true); //为每一个轮廓都查找凸包
}
for (int i = 0; i < contours.size(); i++)
{
drawContours(dst, contours, i, Scalar(0, 255, 255), 2, 8); //绘制轮廓
drawContours(dst, hull, i, Scalar(0, 255, 0), 2, 8); //绘制轮廓
}
imshow("hull", dst);
waitKey(0);
}
ImageWatch
3.绘制轮廓的外接矩形 Rectangle1
#include
#include
#include
#include
using namespace std;
using namespace cv;
int main()
{
Mat src = imread("1.png"); //读取图像
Mat dst = src.clone(); //原图的克隆图像
cvtColor(src, src, COLOR_BGR2GRAY); //灰度化
threshold(src, src, 100, 255, THRESH_BINARY_INV); //二值化
//imshow("src", src);
vector> contours;
vector hierarchy;
findContours(src, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_NONE); //查找轮廓
//画出轮廓并绘制矩形
vector boundRect(contours.size()); //定义外接矩形的集合
drawContours(dst, contours, -1, Scalar(0, 255, 255), 2, 8); //绘制轮廓
//遍历每一个轮廓,对每一个轮廓画 Rectangle1
for (int i = 0; i < contours.size(); i++)
{
boundRect[i] = boundingRect((Mat)contours[i]); //查找每一个外界矩形
rectangle(dst, boundRect[i], Scalar(0,255,0),2,8);
}
imshow("dst", dst);
waitKey(0);
}
4.绘制轮廓的最小外接矩形 Rectangle2