Обработанное изображение Если вы посмотрите на первую строку изображения выше, вы заметите, что, хотя сценарий идентифицирует большинство символов, последовательность неправильно. Я ожидаю, что первые 5 символов будут обработаны как B A J L A, но процесс будет выглядеть как B A J A L, и это продолжается дальше по строке. Мне не удалось выяснить закономерность, по которой это происходит.
Исходное изображение
Изображение выше — это то, что я использую для тестирования.
Код: Выделить всё
import cv2
import numpy as np
import pytesseract
def process_grid(filename):
img = cv2.imread(filename)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV + cv2.
THRESH_OTSU)[1]
items = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = items[0] if len(items) == 2 else items[1]
img_contour = img.copy()
bounding_boxes = [cv2.boundingRect(c) for c in contours]
contours, bounding_boxes = zip(*sorted(zip(contours, bounding_boxes),
key=lambda b: (b[1][1], b[1][0])))
detected = ""
counter = 0
success = 0
failed = 0
img_cropped = ""
detected = ""
for c in contours:
x, y, w, h = cv2.boundingRect(c)
ratio = h/w
area = cv2.contourArea(c)
base = np.ones(thresh.shape, dtype=np.uint8)
if ratio > 0.1 and 100 < area < 10000:
base[y:y+h, x:x+w] = thresh[y:y+h, x:x+w]
segment = cv2.bitwise_not(base)
custom_config = r'-l eng --oem 3 --psm 10 -c
tessedit_char_whitelist="ABCDEFGHIlJKLMNOPQRSTUVWXYZ" '
identified = pytesseract.image_to_string(segment,
config=custom_config)
counter = counter + 1
detected = detected + identified
img_cropped = img[y:y+h, x:x+w]
print(f'counter: {counter} - char: {identified.strip()}')
if len(identified.strip()) > 0:
temp_text = str(counter) + " - " + identified.strip()
cv2.rectangle(img_contour, (x, y), (x+w, y+h), (0, 255, 0), 2)
tracker = cv2.putText(img_contour, temp_text, (x+w, y+h-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 0, 0), 1)
success = success + 1
else:
temp_text = str(counter) + " - "
cv2.rectangle(img_contour, (x, y), (x+w, y+h), (0, 0, 255), 2)
tracker = cv2.putText(img_contour, temp_text, (x+w, y+h-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 0, 225), 1)
failed = failed + 1
print("Counter: " + str(counter))
print("Success: " + str(success))
print("Failed: " + str(failed))
cv2.imwrite("tracker.jpeg", tracker)
process_grid("IMG_2878.JPG")
Надеюсь на информацию/руководство по улучшение сортировки контуров, чтобы они были последовательными.
Подробнее здесь: https://stackoverflow.com/questions/787 ... and-y-axis