首页 > 解决方案 > Pytesseract 循环错误

问题描述

我正在尝试循环 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

标签: pythonocrpython-tesseract

解决方案


n是函数的局部变量get_string。使用缩进,该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.

推荐阅读