导 读
本文主要介绍交流群里的两个实例,直接放源码。(公众号:OpenCV与AI深度学习)
实例一 要求:识别下图中加粗的文本内容。
实现步骤: 【1】闭运算减少线条干扰
import numpy as np import cv2 img= cv2.imread('test.jpg') #cv2.imshow('src', img) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) _,thres = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV cv2.THRESH_OTSU) k1=np.ones((9,9), np.uint8) close = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, k1) cv2.imwrite('close.jpg', close) cv2.imshow('close', close) cv2.waitKey(0) cv2.destroyAllWindows() print("Done!")
【2】OCR识别,参考下面以前的文章即可
让OCR更简单 | PaddleOCR OpenCV实现文字识别步骤与代码演示
实战 | OpenCV OCR实现环形文字识别实例(详细步骤 代码)
实例二 要求:识别下图中圆形锡点的数量和位置。
实现步骤: 【1】转为灰度图、中值滤波
【2】灰度图和滤波图差分、阈值分割
【3】形态学处理
【4】轮廓筛选、标注结果
完整源码:
代码语言:javascript复制import numpy as np
import cv2
font=cv2.FONT_HERSHEY_SIMPLEX
img = cv2.imread('AA.png')
cv2.imshow('src', img)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.medianBlur(gray,15)
cv2.imwrite('blur.jpg',blur)
cv2.imshow('blur', blur)
diff = cv2.absdiff(gray, blur)
cv2.imshow('diff', diff)
cv2.imwrite('diff.jpg',diff)
ret,thres = cv2.threshold(diff,15,255,cv2.cv2.THRESH_BINARY)
cv2.imshow('thres', thres)
cv2.imwrite('thres.jpg',thres)
k1 = np.zeros((19, 19),np.uint8)
cv2.circle(k1,(9,9),9,(1,1,1),-1,cv2.LINE_AA)
closing = cv2.morphologyEx(thres, cv2.MORPH_CLOSE, k1, None, None, 1)#闭运算
cv2.imshow('closing',closing)
k2 = np.zeros((13, 13),np.uint8)
cv2.circle(k2,(6,6),6,(1,1,1),-1,cv2.LINE_AA)
opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, k2, None, None, 1)#闭运算
cv2.imshow('opening',opening)
cv2.imwrite('opening.jpg',opening)
contours,hierarchy = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
count = 0
for cnt in contours:
center,radius = cv2.minEnclosingCircle(cnt)
if radius < 15 or radius > 30 or center[1] > 750 or (center[1] > 300 and center[1] < 520):
continue
count = count 1
ROI = opening[int(center[1]-(radius)):int(center[1] radius),int(center[0]-radius):int(center[0] radius)]
dt = cv2.distanceTransform(ROI,cv2.DIST_L2,5,cv2.DIST_LABEL_PIXEL)
transImg = cv2.convertScaleAbs(dt)
cv2.normalize(transImg, transImg, 0, 255, cv2.NORM_MINMAX)
_, _, _, max_loc = cv2.minMaxLoc(transImg)
center = (max_loc[0] center[0]-radius,max_loc[1] center[1]-radius)
#cv2.circle(img,(int(center[0]),int(center[1])),int(radius),(0,255,0),2)
#cv2.circle(img,(int(center[0]),int(center[1])),24,(0,255,0),2)
cv2.circle(img,(int(center[0]),int(center[1])),24,(0,255,0),2)
cv2.drawMarker(img,(int(center[0]),int(center[1])),(0,0,255),
cv2.MARKER_CROSS, 20,2,8)
strCount = "count = %d" % count
cv2.putText(img,strCount,(10,60),font,1.5,(0,255,255),3)
cv2.imshow('result', img)
cv2.imwrite('result.jpg', img)
cv2.waitKey(0)
cv2.destroyAllWindows()