一:开操作(先腐蚀后膨胀)
特点:消除噪点,去除小的干扰块,而不影响原来的图像
import cv2 as cv import numpy as np def camp(val1,val2): pv = val1 + val2 if pv > 255: return 255 if pv < 0: return 0 return pv def open_demo(image): gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY) for i in range(1000): #为灰度图像加一些噪点 h = np.random.random_integers(0,gray.shape[0]-1) w = np.random.random_integers(0, gray.shape[1]-1) val = np.random.random_integers(0, 255) gray[h,w] = camp(gray[h,w],val) ret,binary = cv.threshold(gray,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU) #生成二值化图像 cv.imshow("binary",binary) kernel = cv.getStructuringElement(cv.MORPH_RECT,(3,3)) binary = cv.morphologyEx(binary,cv.MORPH_OPEN,kernel) #开操作,先腐蚀后膨胀,会消除一些为1的白色噪点 cv.imshow("open_demo",binary) src = cv.imread("./o.png") #读取图片 cv.namedWindow("input image",cv.WINDOW_AUTOSIZE) #创建GUI窗口,形式为自适应 cv.imshow("input image",src) #通过名字将图像和窗口联系 open_demo(src) cv.waitKey(0) #等待用户操作,里面等待参数是毫秒,我们填写0,代表是永远,等待用户操作 cv.destroyAllWindows() #销毁所有窗口
二:闭操作(先膨胀后腐蚀)
特点:可以填充闭合区域
def close_demo(image): gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY) ret,binary = cv.threshold(gray,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU) cv.imshow("binary",binary) kernel = cv.getStructuringElement(cv.MORPH_RECT,(15,15)) binary = cv.morphologyEx(binary,cv.MORPH_CLOSE,kernel) cv.imshow("close_demo",binary) src = cv.imread("./o.png") #读取图片 cv.namedWindow("input image",cv.WINDOW_AUTOSIZE) #创建GUI窗口,形式为自适应 cv.imshow("input image",src) #通过名字将图像和窗口联系
三:利用开操作完成的任务
(一)提取水平垂直线
def open_demo(image): gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY) ret,binary = cv.threshold(gray,0,255,cv.THRESH_BINARY_INV|cv.THRESH_OTSU) cv.imshow("binary",binary) kernel = cv.getStructuringElement(cv.MORPH_RECT,(1,15)) #修改内核为(15,1)可以提起横线 binary = cv.morphologyEx(binary,cv.MORPH_OPEN,kernel) cv.imshow("open_demo",binary)
原理:
kernel = cv.getStructuringElement(cv.MORPH_RECT,(15,1))
(二)消除干扰线
def open_demo(image): gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY) ret,binary = cv.threshold(gray,0,255,cv.THRESH_BINARY_INV|cv.THRESH_OTSU) cv.imshow("binary",binary) kernel = cv.getStructuringElement(cv.MORPH_RECT,(3,3)) #因为干扰线很细,小于我们想要的字母,先腐蚀后膨胀对字母无影响,但是对于细线在腐蚀的时候就处理掉了 binary = cv.morphologyEx(binary,cv.MORPH_OPEN,kernel) cv.imshow("open_demo",binary)
(三)提取满足要求的形状
getStructuringElement我们设置的内核形状为矩形,是可以设置其他形状
矩形:MORPH_RECT;
交叉形:MORPH_CORSS;
椭圆形:MORPH_ELLIPSE;
def open_demo(image): gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY) ret,binary = cv.threshold(gray,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU) cv.imshow("binary",binary) kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE,(5,5)) binary = cv.morphologyEx(binary,cv.MORPH_OPEN,kernel) cv.imshow("open_demo",binary)