Обнаружение текста с использованием openCV и Tesseract From Specific Pattern

введите описание изображения здесь

Я хочу нарисовать ограничивающую рамку для всего вопроса и соответствующих вариантов этого вопроса, затем я хочу извлечь текст из каждого из них и поместить в фрейм данных pandas, который будет экспортирован в Excel позже. Для этого у меня есть файл python, который определяет четыре варианта [(a), (b), (c), (d)] и вопрос. Но проблема здесь в том, когда я извлекаю все изображение (без какой-либо ограничивающей рамки) PyTesseract дает мне желаемый результат, но когда я пытаюсь извлечь его из оконных блоков, он делает много ошибок при обнаружении текста. Я прикрепил свой файл Python ниже. Может кто-нибудь подскажет, как правильно определять текст из этих ограничивающих рамок?

Код Python:

 # read the image using OpenCV
image = cv2.imread("E:\PythonTarget.jpg")

# make a copy of this image to draw in
image_copy = image.copy()
# the target word to search for
target_word_a = "(a)"
target_word_b = "(b)"
target_word_c = "(c)"
target_word_d = "(d)"

# get all data from the image
data = tess.image_to_data(image, output_type=tess.Output.DICT)
# get all occurences of the that word
word_occurences_a = [i for i, word in enumerate(data["text"]) if word.lower() == target_word_a]
word_occurences_b = [i for i, word in enumerate(data["text"]) if word.lower() == target_word_b]
word_occurences_c = [i for i, word in enumerate(data["text"]) if word.lower() == target_word_c]
word_occurences_d = [i for i, word in enumerate(data["text"]) if word.lower() == target_word_d]

for occ in word_occurences_a:
    # extract the width, height, top and left position for that detected word
    w = data["width"][occ] + 1000
    h = data["height"][occ]
    l = data["left"][occ]
    t = data["top"][occ]
    # define all the surrounding box points
    p1 = (l, t)
    p2 = (l + w, t)
    p3 = (l + w, t + h)
    p4 = (l, t + h)

    # draw the 4 lines (rectangular)
    image_copy = cv2.line(image_copy, p1, p2, color=(255, 0, 0), thickness=4)
    image_copy = cv2.line(image_copy, p2, p3, color=(255, 0, 0), thickness=4)
    image_copy = cv2.line(image_copy, p3, p4, color=(255, 0, 0), thickness=4)
    image_copy = cv2.line(image_copy, p4, p1, color=(255, 0, 0), thickness=4)

    #Turn the bounding box to a cv2 image
    crop = image_copy[t: t + h, l:l + w]
    #Extract text from the cv2 image
    results = tess.image_to_string(crop)
    #print the extracted text
    print(results)

person Koushik    schedule 11.03.2021    source источник
comment
можно ли поделиться исходным изображением? или загруженное изображение является неизмененным исходным изображением?   -  person Ahx    schedule 11.03.2021
comment
Да, загруженное изображение является оригинальным.   -  person Koushik    schedule 11.03.2021


Ответы (1)


  • Я хочу нарисовать ограничительную рамку для всех вопросов и соответствующих вариантов этого вопроса

Вы можете использовать image_to_data для рисования ограничивающих рамок. Например:

введите описание изображения здесь

  • когда я пытаюсь извлечь его из будинговых боксов, он делает много ошибок при обнаружении текста

Вам следует попробовать использовать режим-сегментации страницы ( psm)

Например, если вы установите psm на 6, предполагая, что изображение представляет собой единый блок текста:

Exracted Recognized
enter image description here Dependence
enter image description here (c) Subordination (d) Slavery
enter image description here (6b) Advance

Код:


# Load the libraries
import cv2
import pytesseract

# Load the image
img = cv2.imread("Uewxg.jpg")

# Convert it to the gray-scale
gry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# OCR detection
d = pytesseract.image_to_data(gry, config="--psm 6", output_type=pytesseract.Output.DICT)

# Get ROI part from the detection
n_boxes = len(d['level'])

# For each detected part
for i in range(n_boxes):

    # Get the localized region
    (x, y, w, h) = (d['left'][i], d['top'][i], d['width'][i], d['height'][i])

    # Draw rectangle to the detected region
    cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 5)

    # Crop the image
    crp = gry[y:y+h, x:x+w]

    # OCR
    txt = pytesseract.image_to_string(crp, config="--psm 6")
    print(txt)

    # Display the cropped image
    cv2.imshow("crp", crp)
    cv2.waitKey(0)

# Display
cv2.imshow("img", img)
cv2.waitKey(0)

person Ahx    schedule 11.03.2021
comment
Хорошо, Thankx @Ahx. Но это не удовлетворяет моим требованиям. В любом случае спасибо за внимание. - person Koushik; 11.03.2021