看看这里,这似乎是确切的答案。
取而代之的是,我的上述代码版本针对文本提取进行了微调(也带有掩码)。
下面是上一篇文章的原始代码,“移植”到python 3、opencv 3,添加了mser和边界框。与我的版本的主要区别在于如何定义分组距离:我的是面向文本的,而下面的一个是自由几何距离。
import sys
import cv2
import numpy as np
def find_if_close(cnt1,cnt2):
row1,row2 = cnt1.shape[0],cnt2.shape[0]
for i in range(row1):
for j in range(row2):
dist = np.linalg.norm(cnt1[i]-cnt2[j])
if abs(dist) < 25: # <-- threshold
return True
elif i==row1-1 and j==row2-1:
return False
img = cv2.imread(sys.argv[1])
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imshow('input', img)
ret,thresh = cv2.threshold(gray,127,255,0)
mser=False
if mser:
mser = cv2.MSER_create()
regions = mser.detectRegions(thresh)
hulls = [cv2.convexHull(p.reshape(-1, 1, 2)) for p in regions[0]]
contours = hulls
else:
thresh = cv2.bitwise_not(thresh) # wants black bg
im2,contours,hier = cv2.findContours(thresh,cv2.RETR_EXTERNAL,2)
cv2.drawContours(img, contours, -1, (0,0,255), 1)
cv2.imshow('base contours', img)
LENGTH = len(contours)
status = np.zeros((LENGTH,1))
print("Elements:", len(contours))
for i,cnt1 in enumerate(contours):
x = i
if i != LENGTH-1:
for j,cnt2 in enumerate(contours[i+1:]):
x = x+1
dist = find_if_close(cnt1,cnt2)
if dist == True:
val = min(status[i],status[x])
status[x] = status[i] = val
else:
if status[x]==status[i]:
status[x] = i+1
unified = []
maximum = int(status.max())+1
for i in range(maximum):
pos = np.where(status==i)[0]
if pos.size != 0:
cont = np.vstack(contours[i] for i in pos)
hull = cv2.convexHull(cont)
unified.append(hull)
cv2.drawContours(img,contours,-1,(0,0,255),1)
cv2.drawContours(img,unified,-1,(0,255,0),2)
#cv2.drawContours(thresh,unified,-1,255,-1)
for c in unified:
(x,y,w,h) = cv2.boundingRect(c)
cv2.rectangle(img, (x,y), (x+w,y+h), (255, 0, 0), 2)
cv2.imshow('result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
样本输出(黄色斑点低于二进制阈值转换,因此被忽略)。红色:原始轮廓,绿色:统一轮廓,蓝色:边界框。
可能不需要使用 MSER,因为简单的 findContours 可能工作正常。
----------------------
在我找到上面的代码之前,从这里开始有我的旧答案。无论如何我都会离开它,因为它描述了几种不同的方法,这些方法可能更容易/更适合某些场景。
一个快速而肮脏的技巧是在 MSER 之前添加一个小的高斯模糊和一个高阈值(或者如果您喜欢花哨的东西,可以进行一些稀释/侵蚀)。在实践中,您只需将文本加粗以填补小空白。显然,您以后可以丢弃此版本并从原始版本中裁剪。
否则,如果您的文本成行,您可以尝试检测平均线中心(例如制作 Y 坐标的直方图并找到峰值)。然后,对于每一行,寻找具有接近平均 X 的片段。如果文本嘈杂/复杂,则非常脆弱。
如果您不需要拆分每个字母,获取整个单词的边界框可能会更容易:只需根据片段之间的最大水平距离(使用轮廓的最左边/最右边的点)分组。然后使用每个组中最左边和最右边的框找到整个边界框。对于多行文本,第一组按质心 Y 坐标。
实施说明:
Opencv 允许您创建直方图,但您可能可以摆脱这样的事情(在类似的任务中为我工作):
def histogram(vals, th=4, bins=400):
hist = np.zeros(bins)
for y_center in vals:
bucket = int(round(y_center / 2.)) <-- change this "2."
hist[bucket-1] += 1
print("hist: ", hist)
hist = np.where(hist > th, hist, 0)
return hist
这里我的直方图只是一个包含 400 个桶的数组(我的图像高 800 像素,所以每个桶捕获两个像素,这就是“2.”的来源)。Vals 是每个片段质心的 Y 坐标(在构建此列表时,您可能希望忽略非常小的元素)。th 阈值只是为了消除一些噪音。你应该得到这样的东西:
0,0,0,5,22,0,0,0,0,43,7,0,0,0
该列表从上到下描述了每个位置有多少个片段。
现在我运行另一遍将峰值合并为一个值(只需扫描数组并在它非零时求和并在第一个零处重置计数)得到类似 {y:count} 的内容:
{9:27, 20:50}
现在我知道我在 y=9 和 y=20 处有两个文本行。现在或之前,您将每个片段分配给在线(在我的情况下再次使用 8px 阈值)。现在您可以单独处理每一行,找到“单词”。顺便说一句,我也遇到了同样的问题,就是字母破损,这就是我来这里寻找 MSER 的原因 :)。请注意,如果您找到单词的整个边界框,则此问题仅发生在第一个/最后一个字母上:其他损坏的字母无论如何都落在单词框内。
这是侵蚀/扩张事物的参考,但高斯模糊/th对我有用。
更新:我注意到这一行有问题:
regions = mser.detectRegions(thresh)
我传入已经阈值的图像(!?)。这与聚合部分无关,但请记住 mser 部分未按预期使用。