Pytesseract loop error
Pytesseract loop error
I'm trying to loop pytesseract code to convert multiple images(18) into strings and name the output in sequece. tried to rearrange and replace the loop position more errors accur.
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 -------")
it returns an error
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 Answer
1
n
is a local variable of the get_string
function. With your indentation, the print
statement is outside this function, so the variable is out of scope, hence the error.
n
get_string
print
Simple code to explain scopes of local variables:
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.
@sanqar Stackoverflow is a question & answer site. This question was about a
NameError
, and I hope I was able to provide an helpful answer. If you have a different problem with a different code, you should post a different question. Before that, I would suggest that you spend some time on a Python tutorial/book to grasp the basics of the language.– Vincent Saulue-Laborde
2 days ago
NameError
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
posted the modified code. no output no error, would you please check it.
– sanqar
Jul 1 at 19:19