如何用OpenCV实现的文档矫正?
摘要:使用 OpenCV 进行文档矫正 本文只发布于博客园与pchar博客 std::vector<std::vector<cv::Point>> cvhel
使用 OpenCV 进行文档矫正
本文只发布于博客园与pchar博客
std::vector<std::vector<cv::Point>> cvhelper::findCorners(const cv::Mat &image) {
cv::Mat gaussImage;
cv::GaussianBlur(image, gaussImage, cv::Size(5, 5), 0);
cv::threshold(gaussImage, gaussImage, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
cv::Canny(gaussImage, gaussImage, 50, 200);
cv::morphologyEx(gaussImage, gaussImage, cv::MORPH_CLOSE,
cv::Mat::ones(5, 5, CV_32F));
std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours(gaussImage, contours, hierarchy, cv::RETR_LIST, cv::CHAIN_APPROX_SIMPLE);
std::vector<std::vector<cv::Point>> ret;
for (auto &contour: contours) {
double peri = cv::arcLength(contour, true);
std::vector<cv::Point> approx;
cv::approxPolyDP(contour, approx, 0.05 * peri, true);
if (approx.size() == 4 && cv::isContourConvex(approx) && cv::contourArea(approx) > 1000) {
ret.push_back(approx);
}
}
return ret;
}
void cvhelper::GetDocumentRect(cv::Mat &src, std::vector<cv::Point> &ret_points) {
int shrunkImageHeight = 500;
cv::Mat shrunkImage;
cv::resize(src, shrunkImage, cv::Size(shrunkImageHeight * src.cols / src.rows, shrunkImageHeight));
cv::cvtColor(shrunkImage, shrunkImage, cv::COLOR_BGR2Luv);
std::vector<cv::Mat> channels;
cv::split(shrunkImage, channels);
std::vector<std::vector<cv::Point>> documentCorners;
for (const auto &channel: channels) {
std::vector<std::vector<cv::Point>> corners = findCorners(channel);
if (!corners.empty()) {
double maxArea = 0.0;
std::vector<cv::Point> maxAreaContourIt;
