#include "ImageApplyDiscardBlank.h" #include "ImageProcess_Public.h" CImageApplyDiscardBlank::CImageApplyDiscardBlank(double threshold, int edge, double devTh, double meanTh, int dilate) : m_threshold(threshold) , m_edge(edge) , m_devTh(devTh) , m_meanTh(meanTh) , m_dilate(dilate) { } CImageApplyDiscardBlank::~CImageApplyDiscardBlank(void) { } void CImageApplyDiscardBlank::apply(cv::Mat& pDib, int side) { if (apply(pDib, m_threshold, m_edge, m_devTh, m_meanTh, m_dilate)) pDib.release(); } void CImageApplyDiscardBlank::apply(std::vector& mats, bool isTwoSide) { (void)isTwoSide; int i = 0; for (cv::Mat& var : mats) { if (i != 0 && isTwoSide == false) break; if (!var.empty()) apply(var, 0); i++; } } bool maxMinCompare(const cv::Mat& img, const cv::Mat& mask, double devTh, double meanTh) { double min, max; cv::minMaxLoc(img, &min, &max, 0, 0, mask); if (cv::mean(img, mask)[0] < meanTh) return false; return (max - min) < devTh; } bool CImageApplyDiscardBlank::apply(const cv::Mat& pDib, double threshold, int edge, double devTh, double meanTh, int dilate) { if (pDib.empty()) return true; double resizeScale = 1.0; while (pDib.cols * resizeScale > 400) resizeScale /= 2; cv::Mat img_resize; cv::resize(pDib, img_resize, cv::Size(), resizeScale, resizeScale, cv::INTER_LINEAR); cv::blur(img_resize, img_resize, cv::Size(3, 3)); //cv::imwrite("img_resize.jpg", img_resize); cv::Mat threshold_img; if (img_resize.channels() == 3) { cv::cvtColor(img_resize, threshold_img, cv::COLOR_BGR2GRAY); cv::threshold(threshold_img, threshold_img, threshold, 255, cv::THRESH_BINARY); } else cv::threshold(img_resize, threshold_img, threshold, 255, cv::THRESH_BINARY); std::vector> contours; std::vector h1; hg::findContours(threshold_img, contours, h1, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE); std::vector contour; for (const std::vector& sub : contours) for (const cv::Point& p : sub) contour.push_back(p); cv::RotatedRect rect = hg::getBoundingRect(contour); rect.size = cv::Size2f(rect.size.width - edge * resizeScale, rect.size.height - edge * resizeScale); cv::Point2f box[4]; rect.points(box); contour.clear(); contours.clear(); for (size_t i = 0; i < 4; i++) contour.push_back(box[i]); contours.push_back(contour); cv::Mat mask = cv::Mat::zeros(img_resize.size(), CV_8UC1); hg::fillPolys(mask, contours, cv::Scalar::all(255)); //cv::imwrite("mask.jpg", mask); bool b = true; if (img_resize.channels() == 3) { cv::Mat bgr[3]; cv::split(img_resize, bgr); for (size_t i = 0; i < 3; i++) { b &= maxMinCompare(bgr[i], mask, devTh, meanTh); if (!b) break; } } else b &= maxMinCompare(img_resize, mask, devTh, meanTh); return b; }