1. 切边

示例代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
 去除图片多余的背景
*/
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

void fetchROI(Mat &img);

int main(){
    string path = "/home/kaijun/Documents/resource/opencv/01_qiebian.jpg";
    Mat src = imread(path,IMREAD_COLOR);
    // 显示图片
    imshow("src",src);
    // 提取感兴趣的区域
    fetchROI(src);

    waitKey(0);
    return 0;
}

void fetchROI(Mat &img){
    // 将彩色图转成灰度图
    Mat gray(img.size(),CV_8UC1);
    cvtColor(img,gray,COLOR_BGR2GRAY);
    imshow("gray",gray);

    // 将图像二值化处理
    Mat binary(img.size(),CV_8UC1);
    threshold(gray,binary,0,255,THRESH_BINARY_INV|THRESH_OTSU);
    imshow("binary",binary);
    // 查找轮廓
    vector<vector<Vec2i>> contours;
    vector<Vec4i> hierarchy;
    findContours(binary,contours,hierarchy,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE);


    RotatedRect resultRect;

    // 遍历轮廓,求轮廓的最大外切矩形
    for(int i = 0; i<contours.size();i++){
        // 取到当前遍历轮廓
        RotatedRect rect = minAreaRect(contours[i]);
        if(rect.size.width > img.size().width*0.75){
            // 绘制轮廓
            //drawContours(img,contours,i,Scalar(0,255,255),2,LINE_AA);
            // 记录外切矩形
            resultRect = rect;
        }
    }

    Mat dst = img(resultRect.boundingRect());

    imshow("dst123",dst);
}