Pytesseract循环错误

时间:2018-06-30 13:11:43

标签: python ocr python-tesseract

我正在尝试循环pytesseract代码以将多个图像(18)转换为字符串,并以顺序命名输出。尝试重新排列和更换回路位置,从而导致更多错误。

import cv2
import numpy as np
import pytesseract
from PIL import Image

src_path = "/home/pi/Desktop/"

def get_string(img_path):

    for n in range(0,18):

        n=n+1

        img = cv2.imread(img_path)

        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        kernel = np.ones((1, 1), np.uint8)
        img = cv2.dilate(img, kernel, iterations=1)
        img = cv2.erode(img, kernel, iterations=1)

        cv2.imwrite(src_path + "removed_noise"+ n +".png",img)
        cv2.imwrite(src_path +"thres"+ n +".png", img)

        result = pytesseract.image_to_string(Image.open(src_path + "thres"+ n +".png"))

    return result

print (get_string(src_path +"sample"+ str(n) +".jpeg"))
print ("------ Done -------")

返回错误

Traceback (most recent call last):
  File "/home/pi/Desktop/imagetostring.py", line 29, in <module>
    print (get_string(src_path +"sample"+ str(n) +".jpeg"))
NameError: name 'n' is not defined

1 个答案:

答案 0 :(得分:0)

nget_string函数的local variable。缩进后,print语句不在此函数范围内,因此变量不在范围内,因此会出错。

用于解释局部变量范围的简单代码:

def someFunction(N):
    print(myLocal) # ERROR: myLocal not defined yet.
    for myLocal in range(1,N):
        print(myLocal) # OK
    print(myLocal) # OK

print(myLocal) # ERROR (your case): myLocal can't be accessed outside someFunction.
               # It doesn't even exist while someFunction is not being executed.