如何检测和识别答案键如给定图像中的数字?

问题描述

我有这张图片,我必须检测并存储答案和相应的问题编号。我尝试使用OCR,但无法正确识别任何内容。还有其他办法吗?

import cv2
from imutils import contours
import numpy as np
import PyTesseract

config = '-l eng+equ --oem 3 --psm 8'

# Load image,grayscale,and adaptive threshold
image = cv2.imread('answerkey.png')
original = image.copy()
original1= image.copy()
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray,255,cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
cv2.imshow("thresh",thresh)
cv2.waitKey(0)

# Filter out all numbers and noise to isolate only Boxes
cnts = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

(cnts,_) = contours.sort_contours(cnts,method="top-to-bottom")
(cnts,method="left-to-right")
print(cnts)
completetext=[]
for c in cnts:
    area = cv2.contourArea(c)
    if 500 < area <5000:
        # cv2.imshow("cnt",original)
        # cv2.waitKey(0)
        x,y,w,h = cv2.boundingRect(c)
        crop = original1[y:y+h,x:x+w]
        gray1 = cv2.cvtColor(crop,cv2.COLOR_BGR2GRAY)
        # cv2.imshow("cropp",crop)
        # cv2.waitKey(0)
        kernel = np.zeros((2,2),np.uint8)
        erode = cv2.erode(gray1,kernel,iterations=2)

        cv2.imshow("cropp erode",erode)
        cv2.waitKey(0)
        text = PyTesseract.image_to_string(erode,config=config)
        print(text)

The Input Image

我直接在整个图像上使用ocr得到错误文本。然后,我尝试对每个块进行裁剪,然后将其放入OCR中,但仍然没有得到很好的效果。 如果有人知道更好的方法,请帮助我

解决方法

尝试:

  1. 删除所有行。
  2. 垂直连接组件(数字)。
  3. 找到轮廓(文本列)并从左到右对其进行排序。
  4. 根据列轮廓对图像进行切片。
  5. 使用适当的psm值白名单数字将单个切片传递到tesseract。

希望这可以解决您的问题。