1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| #include <opencv.hpp> #include <iostream> #include <string>
using namespace cv; using namespace std;
Mat ImageSharp(const Mat& src, int nAmount) { Mat dst; double sigma = 3; float amount = nAmount / 100.0f;
Mat imgBlurred; cv::GaussianBlur(src, imgBlurred, cv::Size(7, 7), sigma, sigma, 4); Mat temp_sub;
cv::subtract(src, imgBlurred, temp_sub); cv::addWeighted(src, 1, temp_sub, amount, 0, dst); return dst; }
Mat ReduceBackGroundAlgorithm(const Mat& src, int flag) { Mat gauss, dst2, dst3; if (flag == 1) { cv::GaussianBlur(src, gauss, cv::Size(31, 31), 0, 0, 4); } else { cv::blur(src, gauss, cv::Size(101, 101)); }
cv::divide(src, gauss, dst2);
dst2 = ImageSharp(dst2, 101); dst2.convertTo(dst3, CV_8UC1, 255); return dst3; }
std::vector<string> readImgs(const string& path) { vector<string> img_path;
vector<cv::String> fn; glob(path, fn, false); size_t count = fn.size();
for (size_t i = 0; i < count; i++) { img_path.push_back(fn[i]); }
return img_path; }
void showImg(const::cv::Mat& img, std::string& w_name) { CV_Assert(!img.empty()); cv::namedWindow(w_name, cv::WINDOW_NORMAL); cv::imshow(w_name, img); }
void getbw(const cv::Mat& src, Mat& dst, double th = 15) { cv::Mat img_src = src.clone(); if (img_src.cols < 1500) { resize(img_src, img_src, img_src.size() * 2, 0, 0, cv::INTER_CUBIC); }
Mat gray, res, res1; cv::cvtColor(img_src, gray, COLOR_BGR2GRAY);
cv::adaptiveThreshold(gray, res, 255, ADAPTIVE_THRESH_MEAN_C, 0, 31, th);
res.convertTo(res1, CV_32FC1, 1.0 / 255);
dst = ReduceBackGroundAlgorithm(res1, 1); }
int main(int argc, char const* argv[]) { string path = "C:\\Users\\YSXCC\\Desktop\\test.jpg"; string save_path = "C:\\Users\\YSXCC\\Desktop\\result"; std::vector<string> imgs = readImgs(path);
for (int i = 0; i < imgs.size(); i++) { Mat src = imread(imgs[i]); if (src.empty()) { return -1; }
std::cout << i << " - " << src.size() << std::endl;
cv::Mat result; getbw(src, result);
string save_filename = save_path + "res_" + to_string(i) + ".png"; cv::imwrite(save_filename, result); std::cout << "finish " + std::to_string(i) << std::endl; }
waitKey(27); return 0; }
|