code_app/modules/imgproc/ImageProcess/ImageApplyDiscardBlank.cpp

115 lines
2.9 KiB
C++

#include "ImageApplyDiscardBlank.h"
#include "ImageProcess_Public.h"
CImageApplyDiscardBlank::CImageApplyDiscardBlank(double threshold, int edge, double devTh, double meanTh)
: m_threshold(threshold)
, m_edge(edge)
, m_devTh(devTh)
, m_meanTh(meanTh)
{
}
CImageApplyDiscardBlank::~CImageApplyDiscardBlank(void)
{
}
void CImageApplyDiscardBlank::apply(cv::Mat& pDib, int side)
{
if (apply(pDib, m_threshold, m_edge, m_devTh))
pDib.release();
}
void CImageApplyDiscardBlank::apply(std::vector<cv::Mat>& 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 scalar_LE(const cv::Scalar& val1, const cv::Scalar& val2)
{
for (int i = 0; i < 3; i++)
if (val1[i] > val2[i])
return false;
return true;
}
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, int blockSize, double devTh, double meanTh)
{
if (pDib.empty())
return true;
cv::Mat img_resize;
cv::resize(pDib, img_resize, cv::Size(), 0.2, 0.2);
cv::Mat threshold_img;
if (img_resize.channels() == 3)
cv::cvtColor(img_resize, threshold_img, cv::COLOR_BGR2GRAY);
cv::threshold(img_resize.channels() == 3 ? threshold_img : img_resize, threshold_img, threshold, 255, CV_THRESH_BINARY);
std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> h1;
hg::findContours(threshold_img, contours, h1, cv::RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
std::vector<cv::Point> contour;
for (const std::vector<cv::Point>& 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 / 2.5, rect.size.height - edge / 2.5);
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::blur(img_resize, img_resize, cv::Size(3, 3));
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);
/*
if (b)
{
cv::imwrite("空白页/img1/" + std::to_string(index) + ".bmp", img_resize);
cv::imwrite("空白页/mask1/" + std::to_string(index) + ".bmp", mask);
}
else
{
cv::imwrite("空白页/img2/" + std::to_string(index) + ".bmp", img_resize);
cv::imwrite("空白页/mask2/" + std::to_string(index) + ".bmp", mask);
}*/
return b;
}