【问题标题】:Can't get output from Tesseract command run through os.system无法从通过 os.system 运行的 Tesseract 命令获取输出
【发布时间】:2016-04-22 00:37:33
【问题描述】:

我创建了一个函数,它循环图像并使用tesseract 库从图像中获取方向。代码如下所示:

def fix_incorrect_orientation(pathName):
    for filename in os.listdir(pathName):
        tesseractResult = str(os.system('tesseract ' + pathName + '/' + filename + ' -  -psm 0'))
        print('tesseractResult: ' + tesseractResult)
        regexObj = re.search('([Orientation:]+[\s][0-9]{1})',tesseractResult)
        if regexObj:
            orientation = regexObj.groups(0)[0]
            print('orientation123: ' + str(orientation))
        else:
            print('Not getting in the Regex.')

变量tesseractResult 的结果总是0。但是在终端中,我会从命令中得到以下结果:

Orientation: 3
Orientation in degrees: 90
Orientation confidence: 19.60
Script: 1
Script confidence: 21.33

我尝试以多种方式捕获os.system 的输出,例如使用Popensubprocess,但没有任何成功。似乎我无法从tesseract 库中获取输出。 那么,我该怎么做呢?

谢谢, 延特

【问题讨论】:

    标签: python subprocess tesseract popen os.system


    【解决方案1】:

    问完问题10分钟后,我找到了办法。首先导入命令:

    import commands
    

    然后下面的代码就可以解决问题了:

    def fix_incorrect_orientation(pathName):
        for filename in os.listdir(pathName):
            tesseractResult = str(commands.getstatusoutput('tesseract ' + pathName + '/' + filename + ' -  -psm 0'))
            print('tesseractResult: ' + tesseractResult)
            regexObj = re.search('([Orientation:]+[\s][0-9]{1})',tesseractResult)
            if regexObj:
                orientation = regexObj.groups(0)[0]
                print('orientation123: ' + str(orientation))
            else:
                print('Not getting in the Regex.')
    

    这将通过commands 库传递命令,并且由于commands 库中的getstatusoutput 而捕获了输出。

    【讨论】:

    • 除非你知道自己在做什么,否则不要使用str()
    • @J.F.Sebastian 那么这样做到底有什么不好/错误的呢?
    • 如果你必须问;你不应该首先使用它。这是草率代码的标志。
    • 我其实从来不知道这一点。所以我最好在没有 str() 的情况下使用它?您是否有任何文章的链接来解释使用 str() 的坏处?
    • 在不了解其作用的情况下使用(通常是不必要甚至有害的)代码称为"cargo-cult programming"
    猜你喜欢
    • 2021-11-07
    • 2011-02-14
    • 1970-01-01
    • 2014-12-01
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多