C/C++ 图像处理(16)------图像轮廓の最小外接矩形

来源:互联网 发布:android内存优化实践 编辑:程序博客网 时间:2024/06/04 01:38

有时做图像处理,会遇到图像中大部分信息是冗余的情况,以下图为例:
这里写图片描述
假设图中黑色部分才是我们需要研究的对象,则外围的一堆白色是我们希望去掉的,这个时候用最小外接矩形来框住黑色部分,进而截取该部分的信息而忽略掉其他的信息变得实用。
下面,就给出查找图像轮廓中最小外接矩形的代码,后面有空再给出在图像中截取外接矩形的部分成为新图像的代码。

#include "opencv2/highgui/highgui.hpp"#include "opencv2/imgproc/imgproc.hpp"using namespace cv;using namespace std;void fineMinAreaRect(Mat &threshold_output){    vector<vector<Point>> contours;    vector<Vec4i> hierarchy;    //寻找轮廓    findContours(threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));    //对每个找到的轮廓创建可倾斜的边界框    vector<RotatedRect> minRect(contours.size());    for (int i = 0; i < contours.size(); i++)    {        minRect[i] = minAreaRect(Mat(contours[i]));    }    //绘出轮廓及其可倾斜的边界框    Mat drawing = Mat::zeros(threshold_output.size(), CV_8UC3);    for (int i = 0; i< contours.size(); i++)    {        Scalar color = Scalar(255, 255, 255);        //绘制轮廓        drawContours(drawing, contours, i, color, 1, 8, vector<Vec4i>(), 0, Point());        Point2f rect_points[4]; minRect[i].points(rect_points);        for (int j = 0; j < 4; j++)            line(drawing, rect_points[j], rect_points[(j + 1) % 4], color, 1, 8);    }    //结果在窗体中显示    imshow("Contours", drawing);}int main(){    Mat src;    Mat src_gray;    /// 加载源图像    src = imread("..\\..\\示例图片\\1.bmp");    /// 转为灰度图并二值化    cvtColor(src, src_gray, CV_BGR2GRAY);    threshold(src_gray, src_gray, 170, 255, CV_THRESH_BINARY);    /// 最小外接矩形    fineMinAreaRect(src_gray);    ///显示结果    imshow("Source", src);    waitKey(0);    return(0);}

实现结果如下:
这里写图片描述

1 0
原创粉丝点击