2017-09-01 199 views
0

我發現這個例子說說SWT輪廓:Extracting text OpenCV提取輪廓

在我的例子(見下文)的作品不錯,但我需要從代碼一兩件事:它檢測矩形(在文本內部)應該被逐一提取。

example

我怎樣才能做到這一點具有下面的代碼?我想到一個循環,但我不知道該怎麼做。

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) 

按照要求,這是原始圖像:

original

+1

安置自己的原始圖像。 – zindarod

+0

添加原始圖像 – Link

回答

1

第一次使用morpological操作,以確保所有的數字都很好地形成和消除噪聲和後記使用findcontour函數來獲取每個數字分別

+0

嗨 看看我的(個體經營)的答案。這似乎做的工作罰款:【答案】(https://stackoverflow.com/questions/46001090/detect-space-between-text-opencv-python/46002089#46002089) – Link

0

使用此代碼來完成這項工作。它檢測圖像中文字/數字的區域。

import cv2 

image = cv2.imread("C:\\Users\\Bob\\Desktop\\PyHw\\images\\test5.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 


idx =0 
# for each contour found, draw a rectangle around it on original image 
for contour in contours: 

    idx += 1 

    # 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) 

    roi = image[y:y + h, x:x + w] 

    cv2.imwrite('C:\\Users\\Bob\\Desktop\\' + str(idx) + '.jpg', roi) 

    cv2.imshow('img',roi) 
    cv2.waitKey(0) 

的代碼是基於這個其他提問/回答:提取文本的OpenCV