/**
去除图片多余的背景
*/
#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);
}