- 拍摄或者扫描图像不是规则的矩形,会对后期处理产生不好影响,需要通过透视变换校正得到正确形状。
- 通过二值分割 + 形态学方法 + Hough直线 +透视变换
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
RNG rng;
int main(int argc, char** argv)
{
Mat src,temp_threshold,temp_mor,temp_contours,temp_hough,dst;
src = imread("../path.jpg");
if (src.empty())
{
cout << "could not load image1..." << endl;
return -1;
}
namedWindow("src", WINDOW_AUTOSIZE);
imshow("src", src);
cvtColor(src, temp_threshold, COLOR_BGR2GRAY);
threshold(temp_threshold,temp_threshold, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
Mat kernel = getStructuringElement(MORPH_RECT, Size(5, 5), Point(-1, -1));
morphologyEx(temp_threshold,temp_mor,MORPH_CLOSE,kernel, Point(-1, -1), 3);
bitwise_not(temp_mor, temp_mor, Mat());
vector<vector<Point>> contours;
vector<Vec4i> hireachy;
findContours(temp_mor, contours, hireachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point());
temp_contours = Mat::zeros(src.size(), CV_8UC3);
for (size_t i = 0; i < contours.size(); i++)
{
Rect rect = boundingRect(contours[i]);
if (rect.width > (src.cols / 2) && rect.width < src.cols - 5)
{
drawContours(temp_contours, contours, static_cast<int>(i), Scalar(255,0,255), 2, 8, hireachy