Opencv3 C++ VS2017 study notes 09 morphological operation application

  • adaptiveThreshold(~gray, bin, 255,    ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 15,-2);
    • Adaptive thresholding operation, only binarization is used here
    • Note that gray should be inverted. Here we have to refer to our background color. I used a white background, so we need to invert it so that the binary image is a black background.
    • Parameters: original image, output image, binarization algorithm, threshold type (no need to be entangled), operation block size (the calculation unit of adaptiveThreshold is the neighborhood block of the pixel, the size of the neighborhood block is determined by this value), bias Shift adjustment amount (± and 0 are both possible)
    • 15 is the size of the neighborhood block. When the adaptive binarization is found to be unsatisfactory, you can adjust it and the offset -2
  • Keep horizontal lines
    • adaptiveThreshold(~gray, bin, 255,    ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 3,-2);
    • Mat hline = getStructuringElement(MORPH_RECT, Size(src0.cols / 15, 1), Point(-1, -1));
  • Keep vertical lines
    • adaptiveThreshold(~gray, bin, 255,    ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 3,-2);
    • Mat vline = getStructuringElement(MORPH_RECT, Size(1, src0.rows/15), Point(-1, -1));
  • Keep letters
    • adaptiveThreshold(~gray, bin, 255,    ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 13,-2);
    • Mat kernel = getStructuringElement(MORPH_RECT, Size(4,4), Point(-1, -1));
#include "pch.h"
#include <iostream>
#include <opencv2/opencv.hpp>
#include <string>

using namespace std;
using namespace cv;

Mat src0, gray, bin, dst;
int main(int argc, char ** argv)
{
	src0 = imread("C:\\Users\\xujin\\Desktop\\ABCD.PNG");
	if (!src0.data)
	{
		cout << "no image";
		return -1;
	}
	namedWindow("src0_image", WINDOW_AUTOSIZE);
	imshow("src0_image", src0);
	cvtColor(src0, gray, COLOR_BGR2GRAY);
	namedWindow("gray_image", WINDOW_AUTOSIZE);
	namedWindow("bin_image", WINDOW_AUTOSIZE);
	imshow("gray_image", gray);

	//二值化
	adaptiveThreshold(~gray, bin, 255,	ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 13,-2);
	//注意gray要取反,这里要参考我们的背景颜色, 我用的是白色背景,所以要取反这样二值图片就是黑色背景
	imshow("bin_image", bin);
	//保留水平线
	Mat hline = getStructuringElement(MORPH_RECT, Size(src0.cols / 15, 1), Point(-1, -1));
	//保留垂直线
	Mat vline = getStructuringElement(MORPH_RECT, Size(1, src0.rows/15), Point(-1, -1));
	//保留字母
	Mat kernel = getStructuringElement(MORPH_RECT, Size(3,3), Point(-1, -1));
	//这里主要是靠kernel的size来抹除细小噪声, 因为噪点比字母要小很多,所以可以靠小的kernel进行抹除

	Mat temp;
	erode(bin, temp, kernel, Point(-1, -1));
	dilate(temp, dst, kernel, Point(-1, -1));

	//erode(bin, temp, vline, Point(-1, -1));
	//dilate(temp, dst, vline, Point(-1, -1));

	namedWindow("dst_image", WINDOW_AUTOSIZE);
	imshow("dst_image", dst);
	waitKey(0);
	return 0;
}

 

Guess you like

Origin blog.csdn.net/Mrsherlock_/article/details/104514674