Как я могу обнаружить распознать текст в форме - PullRequest
1 голос
/ 02 апреля 2020

нужна ваша помощь. Сейчас я пишу python скрипт для распознавания текста в форме. Эта форма может быть получена с RTSP (IP-камеры) под любым углом. Для примера см. Прикрепленный файл. Мой код здесь, но координаты для обрезки повернутой формы устанавливаются вручную

import cv2
import numpy as np


def main():
    fn  = cv2.VideoCapture("rtsp://admin:Admin123-@172.16.10.254")
    flag, img = fn.read()
    cnt = np.array([
            [[64, 49]],
            [[122, 11]],
            [[391, 326]],
            [[308, 373]]
        ])
    print("shape of cnt: {}".format(cnt.shape))
    rect = cv2.minAreaRect(cnt)
    print("rect: {}".format(rect))

    box = cv2.boxPoints(rect)
    box = np.int0(box)

    print("bounding box: {}".format(box))
    cv2.drawContours(img, [box], 0, (0, 255, 0), 2)

    img_crop, img_rot = crop_rect(img, rect)

    print("size of original img: {}".format(img.shape))
    print("size of rotated img: {}".format(img_rot.shape))
    print("size of cropped img: {}".format(img_crop.shape))

    new_size = (int(img_rot.shape[1]/2), int(img_rot.shape[0]/2))
    img_rot_resized = cv2.resize(img_rot, new_size)
    new_size = (int(img.shape[1]/2)), int(img.shape[0]/2)
    img_resized = cv2.resize(img, new_size)

    cv2.imshow("original contour", img_resized)
    cv2.imshow("rotated image", img_rot_resized)
    cv2.imshow("cropped_box", img_crop)

    # cv2.imwrite("crop_img1.jpg", img_crop)
    cv2.waitKey(0)

def crop_rect(img, rect):
    # get the parameter of the small rectangle
    center = rect[0]
    size = rect[1]
    angle = rect[2]
    center, size = tuple(map(int, center)), tuple(map(int, size))

# get row and col num in img
height, width = img.shape[0], img.shape[1]
print("width: {}, height: {}".format(width, height))

M = cv2.getRotationMatrix2D(center, angle, 1)
img_rot = cv2.warpAffine(img, M, (width, height))

img_crop = cv2.getRectSubPix(img_rot, size, center)

return img_crop, img_rot


if __name__ == "__main__":
    main()

пример pi c

1 Ответ

0 голосов
/ 02 апреля 2020

Вы можете начать с примера из следующего поста .
Пример кода обнаруживает номерной знак, а также определяет вашу «форму» с текстом.

После определения «формы» с текстом вы можете использовать следующие этапы:

  • Применить порог обрезанной области.
  • Найти контуры и найти контур с максимальной площадью.
  • Создайте маску и область маски вне контура (как в примере с номерным знаком).
  • Используйте minAreaRect (как прокомментировал fmw42) и получите угол прямоугольника.
  • Поворот области обрезки (на angle+90 градусов).
  • Применение распознавания текста с использованием pytesseract.image_to_string.

Вот полный код:


Результат вывода OCR:

 AB12345
DEPARTMENT OF
INFORMATION

COMMUNICATION
TECHNOLOGY

cropped:

enter image description here

thresh:
enter image description here

test:
enter image description here

rotated_cropped :
enter image description here

...