I am newbie to OpenCV. I’m trying to find the contours of the captcha image. It does not work only when my captcha image contains the dotted text.
I have done following code for that:
JavaScript
x
26
26
1
import numpy as np
2
import cv2 as cv
3
import imgaug.augmenters as iaa
4
5
im = cv.imread('dataset/1.jpg')
6
imgray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)
7
8
imgray = cv.threshold(imgray, 127, 255, 0)[1]
9
10
dst = cv.Canny(imgray,0,150)
11
blured = cv.blur(dst,(5,5),0)
12
img_thresh = cv.adaptiveThreshold(blured,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY_INV, 11, 2)
13
14
kernel = cv.getStructuringElement(cv.MORPH_RECT, (3,3))
15
threshed = cv.morphologyEx(img_thresh,cv.MORPH_CLOSE,kernel)
16
17
contours, hierarchy = cv.findContours(dst, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
18
print(len(contours))
19
# cv.drawContours(im, contours, -1, (0, 255, 0), 3)
20
21
cv.imshow("img_thresh",img_thresh)
22
cv.imshow("dst",dst)
23
cv.imshow("threshed",threshed)
24
cv.waitKey(0)
25
cv.destroyAllWindows()
26
Can anyone help in this? Is there any way to find contours in this image?
Advertisement
Answer
Here is my code and output
JavaScript
1
32
32
1
'''
2
contours
3
'''
4
import numpy as np
5
import cv2
6
7
#read image as gray
8
pic = r'C:UsersbalajiDesktopcaptcha.jpg'
9
img_color = cv2.imread(pic)
10
cv2.imshow('CAPTCHA preview',img_color)
11
cv2.waitKey(0)
12
13
img_gray = cv2.cvtColor(img_color,cv2.COLOR_BGR2GRAY)
14
15
#Apply thresholding to the image
16
ret, thresh = cv2.threshold(img_gray, 127, 255, cv2.THRESH_OTSU)
17
cv2.imshow('Thresholded image', thresh)
18
cv2.waitKey(0)
19
20
#Dilated image - to connect the dots
21
krn = np.ones((3,3), np.uint8)
22
img_dilated = cv2.dilate(cv2.bitwise_not(thresh), kernel=krn, iterations=1)
23
cv2.imshow('Dilated image', img_dilated)
24
cv2.waitKey(0)
25
26
# Finding and draw Contours
27
contours, hierarchy = cv2.findContours(img_dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
28
black_canvas = np.zeros_like(img_color)
29
cv2.drawContours(black_canvas, contours, -1, (0, 255, 0), 1)
30
cv2.imshow('Contoured image', black_canvas)
31
cv2.waitKey(0)
32