【发布时间】:2018-02-10 16:24:36
【问题描述】:
我找到了这个关于 SWT 轮廓的示例:Extracting text OpenCV
在我的示例(如下)中效果很好,但我需要从代码中再做一件事:它检测到的矩形(在文本内)应该被一一提取。
如何使用以下代码做到这一点?我想到了一个循环,但我不知道该怎么做。
import cv2
image = cv2.imread("card.png")
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # grayscale
_,thresh = cv2.threshold(gray,150,255,cv2.THRESH_BINARY_INV) # threshold
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
dilated = cv2.dilate(thresh,kernel,iterations = 13) # dilate
_, contours, hierarchy = cv2.findContours(dilated,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) # get contours
# for each contour found, draw a rectangle around it on original image
for contour in contours:
# get rectangle bounding contour
[x,y,w,h] = cv2.boundingRect(contour)
# discard areas that are too large
if h>300 and w>300:
continue
# discard areas that are too small
if h<40 or w<40:
continue
# draw rectangle around contour on original image
cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,255),2)
# write original image with added contours to disk
cv2.imwrite("contoured.jpg", image)
根据要求,这是原始图像:
【问题讨论】:
-
发布您的原始图片。
-
添加原图
标签: python opencv bounding-box