首页 > 解决方案 > 如何使用open cv和python检测和识别固定位置的手写矩阵数

问题描述

我的项目遇到了一些问题。我的输出和代码附在下面。我需要的输出只是检测和识别学生的矩阵数字(红色框中的数字是我需要的输出),但我不知道为什么我的输出包括对学生分数的检测和识别(8、3、5、7. .....) 如下所示。这是因为,在我的代码中,我使用 cv.rectangle() 函数绘制了矩阵数,并在进行图像预处理和数字检测和识别之前对其进行裁剪。有人知道吗?谢谢你。

输出:

在此处输入图像描述

代码:

def proc_user_image(test_img_file, model):
    print('Loading "%s for digit recognition" ...' % test_img_file) #(Output)
    Test_Img_num = 0

    for load_detect_img in glob.glob(TEST_USER_IMG):
        im = cv2.imread(load_detect_img)
   
        matrix = cv2.rectangle(im,(640,560),(1500,670),(0,255,0),2)
        imgray = cv2.cvtColor(matrix, cv2.COLOR_BGR2GRAY)
        cropped_matrix=None
        cropped_matrix=imgray[560:670, 640:1500]
   
        kernel = np.ones((5,5),np.uint8)
        ret,thresh = cv2.threshold(cropped_matrix, 127,255,0)
        kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (4,8))
        morph_img = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

        canny_edge = cv2.Canny(imgray,170,200)

        contours, new = cv2.findContours(canny_edge.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
        contours = sorted(contours,key=cv2.contourArea,reverse=True)[:30] 
        
        digits_rectangles = get_digits(contours,new)

        for rect in digits_rectangles:
            x,y,w,h = rect
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
        
            im_digit = imgray[y:y+h, x:x+w]
            im_digit = (255-im_digit)
            im_digit = imresize(im_digit,(IMG_WIDTH, IMG_HEIGHT))

            hog_img_data = pixels_to_hog_20([im_digit])
            pred = model.predict(hog_img_data)
            cv2.putText(im, str(int(pred[0])), (x,y), cv2.FONT_HERSHEY_SIMPLEX, 2, (255,0,0), 3)
            print("test", str(int(pred[0])))
        
        resize= imresize(matrix,(500, 700))
        cv2.imshow("Test", resize)
        cv2.waitKey(0)

`

通过作物部分的输出:

在此处输入图像描述

标签: pythonopencvimage-processingcoordinatessvm

解决方案


推荐阅读