I am trying to implement one of the stages of the OCR system. The character segmentation stage. The code is shown below. The code is quite simple:
- the image is being read
- grayscale image translation
- image binarization
- application of dilation operation
- selection of contours
It is assumed that each selected contour is a symbol.
The results of the algorithm are not satisfactory. Sometimes-the characters stand out well. Sometimes only parts of characters are highlighted, sometimes several characters are highlighted. Please help with the code, I really want it to correctly highlight the characters.
UPDATE 1. I am trying to implement a character segmentation system for different fonts. It turned out that there are no universal parameters of erosion and dilation operations for different fonts
Test image:
Result of character selection 1 (Small parts of characters):
Result of character selection 2 (Big parts of characters):

Full result (All parts of characters):
import cv2
import numpy as np
def letters_extract(image_file):
img = cv2.imread(image_file)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
img_dilate = cv2.dilate(thresh, np.ones((1, 1), np.uint8), iterations=1)
# img_erode = cv2.erode(img_dilate, np.ones((3, 3), np.uint8), iterations=1)
# Get contours
contours, hierarchy = cv2.findContours(img_dilate, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
letters = []
for idx, contour in enumerate(contours):
(x, y, w, h) = cv2.boundingRect(contour)
if hierarchy[0][idx][3] == 0:
letter_crop = gray[y:y + h, x:x + w]
letters.append(letter_crop)
cv2.imwrite(r'D:\projects\proj\test\tnr\{}.png'.format(idx), letter_crop)
return letters
letters_extract(r'D:\projects\proj\test\test_tnr.png')



