M.Mehranian
M.Mehranian

Reputation: 167

Finding contours of a two-part letter

Suppose that I have an image of letters and I want to find the region of those letters.

I have wrote this code:

MIN_CONTOUR_AREA = 10   
img = cv2.imread("alphabets.png")     
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)    
blured = cv2.blur(gray, (5,5), 0)    
img_thresh = cv2.adaptiveThreshold(blured, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
imgContours, Contours, Hierarchy = cv2.findContours(img_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for contour in Contours:
    if cv2.contourArea(contour) > MIN_CONTOUR_AREA:
        [X, Y, W, H] = cv2.boundingRect(contour)
        cv2.rectangle(img, (X, Y), (X + W, Y + H), (0,0,255), 2)
cv2.imshow('contour', img)

But the code above has this output: result

What can I do to find contour for letters that are not continuous like 'i' or Arabic letters?

Upvotes: 6

Views: 2773

Answers (2)

Yasin Asadnezhad
Yasin Asadnezhad

Reputation: 189

I have this problem. I fix it to this way. add this code :

dst = cv2.Canny(gray, 0, 150)

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)    
  dst = cv2.Canny(gray, 0, 150)
blured = cv2.blur(dst, (5,5), 0)    
img_thresh = cv2.adaptiveThreshold(blured, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
imgContours, Contours, Hierarchy = cv2.findContours(img_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for contour in Contours:
    if cv2.contourArea(contour) > MIN_CONTOUR_AREA:
        [X, Y, W, H] = cv2.boundingRect(contour)
        cv2.rectangle(img, (X, Y), (X + W, Y + H), (0,0,255), 2)
cv2.imshow('contour', img)

Upvotes: 0

Salman
Salman

Reputation: 1006

Before finding the contours, you can use some segmentation methods:

rect_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (30, 10))
threshed = cv2.morphologyEx(img_thresh, cv2.MORPH_CLOSE, rect_kernel)

enter image description here

and after applying cv2.findContours the result will be like this:

enter image description here

Upvotes: 7

Related Questions