2. 切边+旋转

示例代码

  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
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
/**
 去除图片多余的背景,切边并且旋转
*/
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

void verifyRotation(Mat &img,Mat &outputImg);
void fetchROI(Mat &img);

int main(){
    string path = "/home/kaijun/Documents/resource/opencv/02_qiebian.jpg";
    Mat src = imread(path,IMREAD_COLOR);
    // 显示图片
    imshow("src",src);

    Mat rotationImg;

    verifyRotation(src,rotationImg);

    fetchROI(rotationImg);

    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);
}


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

    // 将图像二值化处理
    Mat binary(img.size(),CV_8UC1);
    threshold(gray,binary,0,255,THRESH_BINARY_INV|THRESH_OTSU);
    imshow("binary1",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(255,0,255),2,LINE_AA);
            // 记录外切矩形
            resultRect = rect;
        }
    }

    // 打印图片需要旋转的角度
    cout<<resultRect.angle<<endl;

    // 先对图片进行旋转
    Point2f center(img.cols/2,img.rows/2);
    Mat matrix = getRotationMatrix2D(center,(resultRect.angle)+90,1);

    warpAffine(img,outputImg,matrix,img.size());

    imshow("rotateimg",outputImg);
}