python - cv2.rectangle 加入最近的边界框
问题描述
我正在尝试在扫描页面中隔离中世纪手稿的文字。我正在使用 cv2 来检测区域 ant id 给了我一个非常令人满意的结果。我用增量编号标记了每个矩形,我担心检测到的区域不连续: 这是一个单词上的 cv2 边界框区域的示例结果
这是我使用的代码:
import numpy as np
import cv2
import matplotlib.pyplot as plt
# This is font for labels
font = cv2.FONT_HERSHEY_SIMPLEX
# I load a picture of a page, gray and blur it
im = cv2.imread('test.png')
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
image_blurred = cv2.GaussianBlur(imgray, (5, 5), 0)
image_blurred = cv2.dilate(image_blurred, None)
ret,thresh = cv2.threshold(image_blurred,0,255,0,cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# I try to retrieve contours and hierarchy on the sample
_, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
hierarchy = hierarchy[0]
# I read every contours and retrieve the bounding box
for i,component in enumerate(zip(contours, hierarchy)):
cnt = component[0]
currentHierarchy = component[1]
precision = 0.01
epsilon = precision*cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,epsilon,True)
# This is the best combination I found to isolate parents container
# It gives me the best result (even if I'm not sure what I'm doing)
# hierarchy[2/3] is "having child" / "having parent"
# I thought currentHierarchy[3] < 0 should be better
# but it gives no result
if currentHierarchy[2] > 0 and currentHierarchy[3] > 0:
x,y,w,h = cv2.boundingRect(approx)
cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
cv2.putText(im,str(i),(x+2,y+2), font, 1,(0,255,0),2,cv2.LINE_AA)
plt.imshow(im)
plt.show()
我想将最近的区域连接在一起,以便对我的页面进行单词标记。在我的示例图片中,我想加入 2835、2847、2864、2878、2870 和 2868。
我应该怎么做 ?我以为我可以将每个框的每个坐标存储在一个数组中,然后测试 (start_x, start_y) 和 (end_x,end_y) - 但对我来说似乎很糟糕。
你能给个提示吗?
谢谢,
解决方案
感谢Jeru Luke,我们可以在一个完整的页面上实现这个尝试。给出的值非常有帮助,总体上对于模糊和侵蚀操作中的内核适应。圣经历史手稿页面上的最终结果非常有趣。我们可以在识别中看到一些“黑洞”,据我所知,膨胀;这是第一个进行中的工作。我们将不得不管理大图片和首字母大写。这是我们用来过滤框、在框上添加标签并将每个片段保存在单独文件中的代码:
for i,component in enumerate(zip(contours, hierarchy)):
cnt = component[0]
currentHierarchy = component[1]
if currentHierarchy[2] > 0 and currentHierarchy[3] > 0:
x,y,w,h = cv2.boundingRect(approx)
if h < 300 and h > 110 and w > 110:
cv2.rectangle(im,(x-5,y-5),(x+w+5,y+h+5),(0,255,0),8)
cv2.putText(im,str(i),(x+2,y+2), font, 1,(0,255,0),2,cv2.LINE_AA)
cv2.putText(im,str(cv2.contourArea(cnt)),(x+w-2,y+h-2), font, 1,(0,255,0),2,cv2.LINE_AA)
cv2.putText(im,str(h)+'/'+str(w),(x+w-2,y+h-2), font, 1,(0,0,255),2,cv2.LINE_AA)
fragment = im[y:y+h, x:x+w]
cv2.imwrite("res" + str(i) + ".png", fragment)
推荐阅读
- c# - 什么是 System.Web.Mvc.WebViewPage 以及我的视图文件如何继承它?
- vba - VBA for Powerpoint:通过选择另一个 Powerpoint 中的按钮来更改幻灯片
- google-chrome-extension - 如何将全局错误处理添加到 chrome 扩展后台脚本?
- python - python 我需要在安装中包含什么
- java - 如何列出所有根集合并获取所有产品?
- python - 如何在python中对具有不同大小和元素大小的元组列表进行排序
- html - 浏览器不会获取字体文件
- vba - VBA用户表单列表框双击事件
- node.js - MongoDB 仅在来自另一个集合的状态为 true 时才返回对象(使用分页)
- windows - PowerShell:断电时启动脚本的最佳方式