我会在执行 OCR 部分之前尝试定位包含文本的区域,使其成为我的 ROI。然后对于 OCR 部分,使用 ROIs 而不是整个图像。然后您可以搜索 ROI 是否包含轮廓,然后它应该执行 OCR 否则会产生空白。希望对您有所帮助,干杯!
例子:
import cv2
import numpy as np
img = cv2.imread('table_so.png')
res = cv2.resize(img,None,fx=0.8, fy=0.8, interpolation = cv2.INTER_CUBIC)
h,w,ch = res.shape
cv2.rectangle(res, (0,0), (w,h), (0,0,0), 10)
gray = cv2.cvtColor(res, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray,220,255,cv2.THRESH_BINARY)
_, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
sort_cnts = sorted(contours, key=lambda ctr: cv2.boundingRect(ctr)[0] + cv2.boundingRect(ctr)[1] * res.shape[1] )
ROIs = []
for cnt in sort_cnts:
x,y,w,h = cv2.boundingRect(cnt)
if 2000 > w > 70 and h < 100:
ROI = res[y:y+h, x:x+w]
ROIs.append(ROI)
cv2.rectangle(res, (x,y), (x+w,y+h), (0,255,0), 2)
for i in ROIs:
roi = i
gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray,220,255,cv2.THRESH_BINARY)
_, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
if len(contours) > 1:
print('DO OCR HERE')
else:
print('BLANK SPACE')
cv2.imshow('img', gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imshow('img', res)
结果:
(绿色框为 ROI)
- 在此处进行 OCR
- 在此处进行 OCR
- 在此处进行 OCR
- 在此处进行 OCR
- 在此处进行 OCR
- 在此处进行 OCR
- 在此处进行 OCR
- 在此处进行 OCR
- 在此处进行 OCR
- 空白空间
- 空白空间
- 空白空间