OpenCV学习 day6 形态学操作应用 提取水平与垂直线
复习一下 膨胀 腐蚀的概念
膨胀:结构元素覆盖下像素的最大值
腐蚀:结构元素覆盖下像素的最小值
提取水平与垂直线步骤:
1. 读取图像imread
2. 转为灰度图cvtColor
3. 转为二值图像adaptiveThreshold
adaptiveThreshold( InputArray src, OutputArray dst, double maxValue, int adaptiveMethod, int thresholdType, int blockSize, double C ); double maxValue //二值图的最大值 int adaptiveMethod //自适应方法 //ADAPTIVE_THRESH_MEAN_C和ADAPTIVE_THRESH_GAUSSIAN_C择其一 int thresholdType //阈值类型 int blockSize //块大小 double C //常量 可以是负数
4. 定义结构元素
5. 开操作(腐蚀+膨胀)
int main(int arg, char** argv) { char image_path[] = "D:/Learning/image/11.png"; //读入原图 Mat src; src = imread(image_path); namedWindow("src", WINDOW_AUTOSIZE); imshow("src", src); //转为灰度图 Mat gray_src; cvtColor(src, gray_src, COLOR_BGR2GRAY); imshow("gray image", gray_src); //转为二值图 Mat binImg; adaptiveThreshold(~gray_src, binImg, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 15, -2); imshow("binImg", binImg); //定义结构元素 Mat hline = getStructuringElement(MORPH_RECT, Size(binImg.cols / 32, 1), Point(-1, -1)); //用于提取水平线 Mat vline = getStructuringElement(MORPH_RECT, Size(1, binImg.rows / 32), Point(-1, -1)); //用于提取垂直线 //开操作 Mat dst, temp; /* erode(binImg, temp, hline); dilate(temp, dst, hline); */ morphologyEx(binImg, dst, MORPH_OPEN, hline); bitwise_not(dst, dst); //反转像素 blur(dst, dst, Size(3, 3), Point(-1, -1)); //让结果更圆滑 imshow("final image", dst); waitKey(0); return 0; }
应用2
去掉文字背后的斜线
//定义结构元素 Mat kernel = getStructuringElement(MORPH_RECT, Size(7, 7), Point(-1, -1)); //开操作 morphologyEx(binImg, dst, MORPH_OPEN, kernel); bitwise_not(dst, dst); //反转像素 blur(dst, dst, Size(3, 3), Point(-1, -1)); //让结果更圆滑
注意的是,前景文字要比背景线更粗,提取效果才会更好
PYTHON实现直线提取:
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15,1)) # 横线 kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1,15)) # 竖线 dst = cv2.morphologyEx(canny, cv2.MORPH_OPEN, kernel)