分割字符
import os
import cv2
import numpy as np
path=os.listdir('D:/HP/library/cv2data')
for i in range(0,len(path)):
endpath=path[i]
#读取图片
#腐蚀操作处理灰度图像
img=cv2.imread('D:/HP/library/cv2data/'+str(endpath),0)
#用于显示轮廓(灰度图吞色彩,无法显示轮廓)
img1=cv2.imread('D:/HP/library/cv2data/'+str(endpath),-1)
#处理图像,二值化处理
th2=cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,20)
#处理后部分图像发生断触,腐蚀(白底,腐蚀之后轮廓变粗)
kernel=np.ones((3,3),np.uint8)
erosion=cv2.erode(th2,kernel,iterations=1)
#dilation=cv2.dilate(th2,kernel,iterations=1)
#读取轮廓
contours,hierarchy=cv2.findContours(erosion,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#imgcopy=np.ones(img.shape,np.uint8)
print(len(contours))
for cnt in contours:
area=cv2.contourArea(cnt)
if int(area)<1000 and int(area)>30:
dst = cv2.drawContours(img1, cnt, -1, (255, 255, 255), 1)
#分割轮廓(最小外界矩形)
x,y,w,h=cv2.boundingRect(cnt)
dst=cv2.rectangle(dst,(x,y),(w+x,y+h),(0,0,255),3)
#显示图片
#创建图集
imgs=np.hstack([th2,erosion])
cv2.namedWindow('img',cv2.WINDOW_NORMAL)
cv2.imshow('img',imgs)
cv2.waitKey(0)
cv2.destroyAllWindows()