Python-使用“ With Module as x”和Threading.Timer

时间:2018-07-03 18:00:19

标签: python multithreading python-3.x ocr

我正在尝试使用Tesserocr来尽可能连续地不断读取不断变化的文本行(现在是每3秒一次,但我希望它变得更频繁)。

现在,我有以下代码:

 from tesserocr import PyTessBaseAPI

 def readingFunction():
     threading.Timer(1.0, readingFunction).start()
     with PyTessBaseAPI() as api:
          # Get image
          img = getImageForOCR()

          # Get OCR Text
          api.SetImage(img)
          return api.GetUTF8Text()

 readingFunction()

这很好用,但是每次函数运行时,都会加载PyTessBaseAPI(),这会使我的代码变慢。如果我在函数外部收到“ with PyTesBaseAPI()..”这样的语句:

 from tesserocr import PyTessBaseAPI


 with PyTessBaseAPI() as api:
     def readingFunction():
          threading.Timer(3.0, readingFunction).start()

          # Get image
          img = getImageForOCR()

          # Get OCR Text                  
          api.SetImage(img)
          return api.GetUTF8Text()

     readingFunction()

..然后它仅在第一次运行良好,但随后在第二次运行(并且计时器触发了下一次运行),我收到以下错误:

Exception in thread Thread-1:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 1182, in run
    self.function(*self.args, **self.kwargs)
File "TestFile.py", line 111, in <module>
    def readingFunction():
File "TestFile.py", line 118, in returnOCRTextFrom
    return api.GetUTF8Text()
File "tesserocr.pyx", line 2111, in tesserocr.PyTessBaseAPI.GetUTF8Text
RuntimeError: Failed to recognize. No image set?

我已经测试过,并且img确实有有效的图像,并且我相信api.SetImage(img)正在运行。

有人可以告诉我我在做什么错吗?

0 个答案:

没有答案