python - 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
解决方案
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.
推荐阅读
- c++ - 系统时间更改时 wait_until 的 condition_variable 解决方法
- linux - 如何从 git repo 构建 python 数据表
- typo3 - 如何在静态扩展排版中设置流体模板的变量值?
- spring - 从 DTO 填充查询参数
- python - 如何使用 python 加速视频而不丢帧
- python - 我正在尝试使用 cv2.projectPoints() 但出现错误
- mysql - 当供应商列出一个事件并且其他访问者能够看到他们当地时间的时间时,如何显示一个时区列表供供应商选择?
- wordpress - 我的 wordpress 网站 URL 被一次又一次地更改
- php - 即使产品已经存在于购物车中,WooCommerce 也始终重定向到结帐
- construct-2 - 构造 - 对网页进行函数调用并提供稍后调用的回调函数