视觉/图像重磅干货,第一时间送达!
导 读
本文主要介绍基于OpenCV+OCR实现弧形文字识别实例,并给详细步骤和代码。
背景介绍
测试图如下,目标是正确识别图中的字符。图片来源:
https://www.51halcon.com/forum.php?mod=viewthread&tid=6712
同样,论坛中已经给出了Halcon实现代码,实现效果如下:
这个例子与以前介绍的环形文字识别类似,具体可参考下面链接:
实战 | OpenCV+OCR实现环形文字识别实例(详细步骤 + 代码)
二者的区别就在于一张包含完整的圆,另一张只有部分圆弧,下面给出详细实现步骤。
实现步骤
【1】扩充图像。由于这里的只有部分圆弧,为方便后续检测圆和ROI截取,我们先将原图扩大:
img = cv2.imread("./1.png")
cv2.imshow("src",img)
new_img = np.zeros((img.shape[0]*3,img.shape[1]*3,3),np.uint8)
new_img[new_img.shape[0]//3:new_img.shape[0]//3+img.shape[0],new_img.shape[1]//3:new_img.shape[1]//3+img.shape[1]] = img
cv2.imshow('new_img',new_img)
【2】检测圆。将扩充后的图像转为灰度图,然后滤波,使用霍夫变换检测圆,结果如下:
gray = cv2.cvtColor(new_img,cv2.COLOR_BGR2GRAY)
gray = cv2.medianBlur(gray,3)
circles = cv2.HoughCircles(gray,cv2.HOUGH_GRADIENT,1,100,\
param1=200,param2=30,minRadius=300,maxRadius=400)
【3】极坐标变换。以检测到的圆心和半径做极坐标变换。
ROI = new_img[y:y+h,x:x+w].copy()
cv2.imshow('ROI',ROI)
cv2.imwrite('ROI.jpg',ROI)
trans_center = (int(center[0]-x), int(center[1]-y))
polarImg = cv2.warpPolar(ROI,(300,600),trans_center,radius,cv2.INTER_LINEAR + cv2.WARP_POLAR_LINEAR)
polarImg = cv2.transpose(polarImg)
polarImg = cv2.flip(polarImg,0)
cv2.imshow('polarImg',polarImg)
【4】使用OCR做字符识别。这里使用EasyOCR或者PaddleOCR均可:
result = reader.readtext(polarImg)
res = None
print(result)
if len(result) > 0:
for i in range(0,len(result)):
print(result[i][1])
if(result[i][2] < 0.2):
continue
print('---------------1--------------')
for j in range(4):
if j > 0:
cv2.line(polarImg,(tuple(result[i][0][j-1])),(tuple(result[i][0][j])),(0,255,0),2,cv2.LINE_AA)
cv2.line(polarImg,(tuple(result[i][0][0])),(tuple(result[i][0][3])),(0,255,0),2,cv2.LINE_AA)
strText = result[i][1].replace(' ','')
cv2.putText(polarImg,strText,(result[i][0][3][0],result[i][0][3][1]+20),0,1.1,(0,0,255),2)
【5】反极坐标变换。通过反极坐标变换,将识别结果映射到原始图像。
polarImg_Inv = cv2.warpPolar(polarImg,(w,h),trans_center,radius,cv2.INTER_LINEAR + \
cv2.WARP_POLAR_LINEAR + cv2.WARP_INVERSE_MAP)
cv2.imshow('polarImg_Inv',polarImg_Inv)
【6】截取ROI,得到最终结果。
ROI = new_img[y:y+h,x:x+w]
for i in range(0,ROI.shape[0]):
for j in range(0, ROI.shape[1]):
if mask[i,j] > 0:
ROI[i,j] = polarImg_Inv[i,j]
#cv2.imshow('ROI',ROI)
res = new_img[new_img.shape[0]//3:new_img.shape[0]//3+img.shape[0],new_img.shape[1]//3:new_img.shape[1]//3+img.shape[1]]
本文分享自 OpenCV与AI深度学习 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!