[Python] Remove noise and lines from the CAPTCHA image

Discussão em 'Python' iniciado por Stack, Maio 15, 2025.

  1. Stack

    Stack Membro Participativo

    I need support to treat a captcha image, I made an algorithm for testing to treat some images that come from a website's captcha and for some types I was able to treat and use tesseract to extract the text successfully! However, there is one of the images that follows a different pattern and I am not able to evolve much, I need to remove these diagonal lines so that I can get the text, follow my code below and the images before and after the treatment. Do you have any ideas on how to help me deal with this stage of these noises that still appear?

    import pytesseract
    import cv2
    from PIL import Image
    import numpy as np

    def limpar_imagem(imagem: Image.Image):
    imagem = imagem.convert('RGB')
    largura, altura = imagem.size
    array = np.array(imagem)

    # Converte para tons inteiros para facilitar comparação
    def rgb_to_hex_val(pixel):
    return (pixel[0] << 16) + (pixel[1] << 8) + pixel[2]

    # Define limites
    escuro_min = 0x000000
    escuro_max = 0x999999
    branco1 = 0xFEFEFE
    branco2 = 0xFAFAFA
    preto = 0x000000

    resultado = array.copy()

    for x in range(1, largura - 1): # evita bordas
    for y in range(altura):
    cor = rgb_to_hex_val(array[y, x])
    if (escuro_min <= cor <= escuro_max) or (cor in [branco1, branco2, preto]):
    viz_esq = rgb_to_hex_val(array[y, x - 1])
    viz_dir = rgb_to_hex_val(array[y, x + 1])
    if escuro_min <= viz_esq <= escuro_max and escuro_min <= viz_dir <= escuro_max:
    resultado[y, x] = array[y, x]

    return Image.fromarray(resultado)

    # Caminho para o Tesseract no Windows
    pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

    metodos = [
    cv2.THRESH_BINARY,
    cv2.THRESH_BINARY_INV,
    cv2.THRESH_TRUNC,
    cv2.THRESH_TOZERO,
    cv2.THRESH_TOZERO_INV,
    ]

    imagem = cv2.imread('image.png')

    # transformar a imagem em escala de cinza
    imagem_cinza = cv2.cvtColor(imagem, cv2.COLOR_RGB2GRAY)

    for index,metodo in enumerate(metodos):
    _, imagem_tratada = cv2.threshold(imagem_cinza, 127, 255, metodo or cv2.THRESH_OTSU)

    cv2.imwrite(f'imagem_tratada_{index}.png', imagem_tratada)

    # Abre a imagem tratada
    imagem = Image.open("imagem_tratada_2.png")

    imagem_array = np.array(imagem)

    # Define os tons que consideras como "cinza"
    limiar_inferior = 100
    limiar_superior = 255

    # Cria uma máscara onde o pixel está dentro do intervalo de cinza
    mascara_cinza = (imagem_array >= limiar_inferior) & (imagem_array <= limiar_superior)

    # Define esses pixels como brancos
    imagem_array[mascara_cinza] = 255
    imagem_array[0:6, :] = 255

    limiar_preto = 30 # Pode ajustar

    # Máscara dos pixels pretos na imagem original
    mascara_preto = imagem_array <= limiar_preto

    # Deixa ainda mais preto (define como 0)
    imagem_array[mascara_preto] = 0

    # Converte de volta para imagem e salva
    imagem_resultado = Image.fromarray(imagem_array)
    imagem_resultado.save('teste/imagemFinal.png')

    imagem = Image.open('teste/imagemFinal.png')

    img = limpar_imagem(imagem)
    img.save("saida_2.png")

    texto = pytesseract.image_to_string(Image.open("saida_2.png"), config='--psm 7')
    print("Texto reconhecido:", texto)


    image to manipulate:

    [​IMG]

    image result:

    [​IMG]

    Continue reading...

Compartilhe esta Página