原图
代码
代码语言:javascript复制 src = cv2.imread("28.png")
gray_src = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
#cv2.imshow("input image", src)
#cv2.imshow("gray image", gray_src)
#cv2.waitKey(0)
gray_src = cv2.bitwise_not(gray_src)
#二值化
binary_src = cv2.adaptiveThreshold(gray_src, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 15, -2)
cv2.namedWindow("result image", cv2.WINDOW_AUTOSIZE)
cv2.imshow("result image", binary_src)
#cv2.waitKey(0)
# 提取水平线 src.shape[1]得到src列数
#hline = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 1), (-1, -1))
hline = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 4), (-1, -1)) #定义结构元素,卷积核
# 提取垂直线 src.shape[0]得到src行数
vline = cv2.getStructuringElement(cv2.MORPH_RECT, (4, 1), (-1, -1))
#vline = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
# 这两步就是形态学的开操作——先腐蚀再膨胀
#temp = cv2.erode(binary_src, hline) #腐蚀
#dst = cv2.dilate(temp, hline) #膨胀
# 开运算
dst = cv2.morphologyEx(binary_src, cv2.MORPH_OPEN, hline) #水平方向
dst = cv2.morphologyEx(dst, cv2.MORPH_OPEN, vline) #垂直方向
#将二指图片的效果反转既黑色变白色,白色变黑色。 非操作
dst = cv2.bitwise_not(dst)
cv2.imshow("Final image", dst)
cv2.waitKey(0)
结果图,还有一些点需要进一步处理
补充知识:Opencv 提取水平 垂直线,去除杂线,提取对象
我就废话不多说了,大家还是直接看代码吧~
代码语言:javascript复制#include<opencv2opencv.hpp
#include<iostream
using namespace std;
using namespace cv;
int main(int argc, char* argv[])
{
Mat src = imread("截图3.jpg");
if (src.empty())
{
return -1;
}
String strInput = "input image";
namedWindow(strInput, CV_WINDOW_AUTOSIZE);
imshow(strInput, src);
Mat dst;
cvtColor(src, dst, CV_BGR2GRAY);//转灰度
imshow("output grap image", dst);
Mat binimg;
adaptiveThreshold(~dst, binimg, 255, ADAPTIVE_THRESH_MEAN_C, ADAPTIVE_THRESH_MEAN_C, 15, -2);//转二值
imshow("binary image", binimg);
Mat hLine = getStructuringElement(MORPH_RECT, Size(src.cols/16, 1), Point(-1, -1));//水平结构
Mat vLine = getStructuringElement(MORPH_RECT, Size(1, src.rows / 16), Point(-1, -1));//垂直结构
Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));//去除杂线 提取对象
Mat tmp;
//erode(binimg, tmp, vLine);
//dilate(tmp, dst, vLine);
morphologyEx(binimg, dst, CV_MOP_OPEN,hLine);
bitwise_not(dst, dst);//取反
blur(dst, dst, Size(3, 3), Point(-1, -1));
imshow("Final image", dst);
waitKey(0);
return 0;
}
以上这篇Python OpenCV去除字母后面的杂线操作就是小编分享给大家的全部内容了,希望能给大家一个参考。