Изображение капчи 6135
Изображение капчи 8892
Теперь у меня есть код для него, и он работает примерно на 50 %. времени, и я не боюсь признаться, что использовал ChatGPT для большей части, если не для всего этого.
Вот оно:
Код: Выделить всё
import cv2
import numpy as np
import pytesseract
# Load image
def clean_image(path: str):
image = cv2.imread(path)
# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply thresholding to get a binary image
_, binary = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY_INV)
# Morphological operations to detect and remove the line
# Use a larger rectangular kernel to detect the horizontal line more effectively
kernel_line = cv2.getStructuringElement(cv2.MORPH_RECT, (40, 4)) # Increase size for more line detection
line_mask = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel_line, iterations=2)
# Subtract the detected line from the original binary image
line_removed = cv2.bitwise_and(binary, cv2.bitwise_not(line_mask))
# Apply median blur to reduce the remaining noise (dots in the background)
blurred = cv2.medianBlur(line_removed, 5) # Increase blur size to target noise
# Apply morphological closing to fill gaps and make digits clearer
kernel_digits = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))
cleaned_image = cv2.morphologyEx(blurred, cv2.MORPH_CLOSE, kernel_digits, iterations=2)
return cleaned_image
custom_config = r'--oem 3 --psm 8 -c tessedit_char_whitelist=0123456789' # Restrict to digits
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
# Run OCR on the cleaned image
for i in range(1,6):
a= clean_image("image"+str(i)+".png")
text = pytesseract.image_to_string(a, config=custom_config).strip()
print("Detected Text:", text, "Length:",len(text))
cv2.imshow("i", a)
cv2.waitKey(0)
cv2.destroyAllWindows()
Результирующее изображение для 6135
Результирующее изображение для 8892
I Я пробовал играть с пороговыми значениями, и 100 кажется «золотым серединой».
Я ожидал, что код выведет текст на изображениях, хотя он дал точный ответ только на половину времени.
Я не разбираюсь в глубоком обучении, и буду использовать его, если не будет другого способа дальнейшей обработки изображений капчи.
Подробнее здесь: https://stackoverflow.com/questions/790 ... seract-ocr