是否可以在将图像传递给tesseract ocr模块之前检查图像的方向

问题描述 投票:1回答:2

对于我当前的ocr项目,我尝试使用tesserect使用python cover pytesseract将图像转换为文本文件。到目前为止,我只是将直接导向的图像传递到我的模块中,因为它能够正确地找出该图像中的文本。但是现在当我传递旋转的图像时,它甚至无法识别单个单词。因此,为了获得良好的结果,我需要以正确的方向传递图像。现在我想知道是否有任何方法可以在将图像传递到ocr模块之前确定图像的方向。请让我知道我可以使用哪些方法进行方向检查。

这是我用来转换的方法:

def images_to_text(testImg):
    print('Reading images form the directory..........')
    dataFile=[]
    for filename in os.listdir(testImg):
        os.chdir(testImg)
        # Define config parameters.
        # '-l eng'  for using the English language 
        # '--oem 1' for using LSTM OCR Engine
        config = ('-l eng --oem 1 --psm 3')
        # Read image from disk
        im = cv2.imread(str(filename), cv2.IMREAD_COLOR)
        # Run tesseract OCR on image
        text = pytesseract.image_to_string(im, config=config)
        #basic preprocessing of the text
        text = text.replace('\t',' ')
        text= text.rstrip()
        text= text.lstrip()
        text = text.replace(' +',' ')
        text = text.replace('\n+','\n')
        text = text.replace('\n+ +',' ')

        #writing data to file
        os.chdir(imgTxt)
        rep=filename[-3:]
        name=filename.replace(rep,'txt')
        with open(name, 'w') as writeFile:
            writeFile.write("%s\n" % text)
        text = text.replace('\n',' ')
        dataFile.append(text)
    print('writing data to file done')    
    return dataFile
image-processing ocr tesseract python-tesseract pytesseract
2个回答
1
投票

@MousamSingh,你不能直接检查图像的方向,因为这是不可能的,因为每当你试图通过tesseract传递图像时它会检测文本并给你回字符串,结果可能有噪音或不必要的文字。

答案 - >在将图像直接传递给tesseract之前,您应首先尝试检测该图像中的文本然后将该文本与边界绑定,最终会在文本周围创建矩形,然后裁剪这些文本并将其传递给tesseract,它会给你更好的结果,因为你关心的是图像的方向。您应该做的是获取框的坐标并使用这些坐标,您将能够找到角度,并且您可以根据需要将该图像旋转到特定角度。

我想这可能会对你有所帮助。如果找到答案,请给它投票。谢谢

是的,我忘了建议你检测文本的方法......

这是python的存储库,可用于检测文本。

github link to python code for text detection

需要帮助请叫我。谢谢


0
投票

我得到了检查图像方向的解决方案。我们已经在pytesseract中有一个方法来完成这项工作。

imPath='path_to_image'
im = cv2.imread(str(imPath), cv2.IMREAD_COLOR)
newdata=pytesseract.image_to_osd(im)
re.search('(?<=Rotate: )\d+', newdata).group(0)

方法pytesseract.image_to_osd(im)的输出是:

Page number: 0
Orientation in degrees: 270
Rotate: 90
Orientation confidence: 4.21
Script: Latin
Script confidence: 1.90

并且我们只需要更改方向的旋转值,因此使用正则表达式将进行进一步的剩余工作。

re.search('(?<=Rotate: )\d+', newdata).group(0)

这将是旋转图像以使其朝向0'方向的最终方法。

def rotate(image, center = None, scale = 1.0):
    angle=360-int(re.search('(?<=Rotate: )\d+', pytesseract.image_to_osd(image)).group(0))
    (h, w) = image.shape[:2]

    if center is None:
        center = (w / 2, h / 2)

    # Perform the rotation
    M = cv2.getRotationMatrix2D(center, angle, scale)
    rotated = cv2.warpAffine(image, M, (w, h))

    return rotated
© www.soinside.com 2019 - 2024. All rights reserved.