如何从图像中逐行提取数字?

2024-06-13 10:52:21 发布

您现在位置:Python中文网/ 问答频道 /正文

在使用opencv对数独板(来自web)的图像进行预处理后,我获得了以下图片:

enter image description here

通过轮廓循环并使用pytesseract和psm 10(单个字符)提取每个值会产生垃圾值

因此,我想将图像分割成行,并尝试使用config psm 6提取值,希望它能起作用

我采用的方法是简单地对行进行numpy切片并尝试提取值,尽管它不起作用,但在第一次迭代后给我SystemError: tile cannot extend outside image,尽管我确信切片发生在图像内部

y = 1
for x in range(1, 9):
     cropped_row = mask[y*33-33:y*33-1][x*33-33:x*33-1]
     text = tess.image_to_string(np.array(cropped_row), config='--psm 6')
     y += 1
     print(text)

我想要一些指导,以正确的方法在OCR行从图像


Tags: 方法text图像imagewebconfig对数图片
2条回答

最后,正如natancy在this答案中解释的那样,我采取了一种稍微不同的方法

我关注网格线,删除了所有值,以便findcontours()将定位所有网格单元

然后,我循环遍历所有轮廓,并检查它们是一个单元(大小)还是其他轮廓。 如果是单元格,则遮罩仅使当前单元格可见(以及按位_和(原始_图像,遮罩)使用时的值) 这样我就可以得到一个只有一个数字的空白图像,然后我通过tesseract运行该图像。 一些文本清除后,我得到了我想要的输出

提取数字:

list_of_clues = []
    for contour in contours:
        extracted_value = ''

        # create black mask
        mask = np.zeros(processed.shape, dtype=np.uint8)

        # check if contour is a cell
        area = cv2.contourArea(contour)
        if 700 <= area <= 1000:  # contour is a cell
            cv2.drawContours(mask, [contour], -1, WHITE, -1)  # color everything in mask, but the contour- white
            isolated_cell = cv2.bitwise_and(processed, mask)
            isolated_cell[mask == 0] = 255  # invert isolated_cell's mask to WHITE (for tess)

            # extract text from isolated_cell
            text = tess.image_to_string(isolated_cell, config=' psm 10')

            # clean non-numbers:
            for ch in text:
                if ch.isdigit():
                    extracted_value = ch

            # calculate cell coordinates only if extracted_value exist
            if extracted_value:
            # relevant for my proj, extract grid coordinates of extracted value
                [x_pos, y_pos, wid, hei] = cv2.boundingRect(contour)    # get contour's sizes
                x_coord = int(x_pos // (grid_size_pixels / 9))          # get x row-coordinate
                y_coord = int(y_pos // (grid_size_pixels / 9))          # get y col-coordinate
                list_of_clues.append(((x_coord, y_coord), int(extracted_value)))
        else:   # contour isn't a cell
            continue

我试过这个:

custom_oem_psm_config = r' oem 3  psm 6 -c tessedit_char_whitelist="0123456789"'# -c preserve_interword_spaces=0'
text= pytesseract.pytesseract.image_to_string(otsu, config=custom_oem_psm_config)
print(text)

输出:

2 91
4 67 13
2 976
4 9
9816 2754
3 1
653 7
24 85 1
46 2

如果您想获得数字的确切位置,请尝试numpy切片并从左到右和从上到下对其进行排序,然后将每个数字传递给tesseract

相关问题 更多 >