Python OpenCV not always recognizing rectangle in captcha

410 Views Asked by At

I have these captchas and was wondering what is the best way to get the section inside of the rectangle border. I tried it and my code can only get like probably 1 in every 4 captchas. Please help, I've been stuck on this for a while now.

Captcha Image

Captcha Image 2

    img = cv2.imread('captcha3.png')
    cropB = cv2.medianBlur(img, 3)
    gray = cv2.cvtColor(cropB, cv2.COLOR_BGR2GRAY)
    white_bg = 255*np.ones_like(img)

    ret, thresh = cv2.threshold(gray, 190, 60, 0)
    im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    for contour in contours:
        approx = cv2.approxPolyDP(contour, 0.01 * cv2.arcLength(contour, True), True)
        (x, y, w, h) = cv2.boundingRect(contour)
        roi = img[y:y + h, x:x + w]
        print(str(w) + " " + str(h))
        if w > 50 and w < 150:
            cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
            white_bg[y:y + h, x:x + w] = roi

    plt.figure("Captcha")
    plt.imshow(imutils.opencv2matplotlib(white_bg))
    plt.show()

To add, sometimes it for some reason decides to make the rectangle less than the rectangle border itself. Like 75% of it when the letters overlay.

0

There are 0 best solutions below