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:
import numpy as np import cv2 as cv import imgaug.augmenters as iaa im = cv.imread('dataset/1.jpg') imgray = cv.cvtColor(im, cv.COLOR_BGR2GRAY) imgray = cv.threshold(imgray, 127, 255, 0)[1] dst = cv.Canny(imgray,0,150) blured = cv.blur(dst,(5,5),0) img_thresh = cv.adaptiveThreshold(blured,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY_INV, 11, 2) kernel = cv.getStructuringElement(cv.MORPH_RECT, (3,3)) threshed = cv.morphologyEx(img_thresh,cv.MORPH_CLOSE,kernel) contours, hierarchy = cv.findContours(dst, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) print(len(contours)) # cv.drawContours(im, contours, -1, (0, 255, 0), 3) cv.imshow("img_thresh",img_thresh) cv.imshow("dst",dst) cv.imshow("threshed",threshed) cv.waitKey(0) cv.destroyAllWindows()
Can anyone help in this? Is there any way to find contours in this image?
Advertisement
Answer
Here is my code and output
''' contours ''' import numpy as np import cv2 #read image as gray pic = r'C:UsersbalajiDesktopcaptcha.jpg' img_color = cv2.imread(pic) cv2.imshow('CAPTCHA preview',img_color) cv2.waitKey(0) img_gray = cv2.cvtColor(img_color,cv2.COLOR_BGR2GRAY) #Apply thresholding to the image ret, thresh = cv2.threshold(img_gray, 127, 255, cv2.THRESH_OTSU) cv2.imshow('Thresholded image', thresh) cv2.waitKey(0) #Dilated image - to connect the dots krn = np.ones((3,3), np.uint8) img_dilated = cv2.dilate(cv2.bitwise_not(thresh), kernel=krn, iterations=1) cv2.imshow('Dilated image', img_dilated) cv2.waitKey(0) # Finding and draw Contours contours, hierarchy = cv2.findContours(img_dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) black_canvas = np.zeros_like(img_color) cv2.drawContours(black_canvas, contours, -1, (0, 255, 0), 1) cv2.imshow('Contoured image', black_canvas) cv2.waitKey(0)