I have a function in python that returns different output of strings (Text). And I have different parts that I should check for the string and if the string is of nine digits or contains 9 digits then I need to perform in the function to exit the function at the point I am newbie at python and I don't know how to exit the function at specific point if a criteria is achieved. For example
s = 'oodf 191876320x sd'
print(any(char.isdigit() for char in s))
This checks if the string has digits. I need to add another criteria to make sure there are adjacent 9 numbers. and if True
, then exit the function at the point.
The code that I am working on is to read number from image (with three different cases of manipulation) This is my try and I welcome any ideas
import pytesseract, cv2, redef readNumber(img):img = cv2.imread(img)gry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)txt = pytesseract.image_to_string(gry)if bool(re.search(r'\d{9}', txt)):return re.findall('(\d{9})\D', txt)[0]blur = cv2.GaussianBlur(img, (3,3), 0)txt = pytesseract.image_to_string(blur)if bool(re.search(r'\d{9}', txt)):return re.findall('(\d{9})\D', txt)[0]thr = cv2.adaptiveThreshold(gry, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 51, 4)txt = pytesseract.image_to_string(thr, config="digits")if bool(re.search(r'\d{9}', txt)):return re.findall('(\d{9})\D', txt)[0]'''try:txt = pytesseract.image_to_string(gry)#txt = re.findall('(\d{9})\D', txt)[0]except:thr = cv2.adaptiveThreshold(gry, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 51, 4)txt = pytesseract.image_to_string(thr, config="digits")#txt = re.findall('(\d{9})\D', txt)[0]return txt
'''# M5Pr5 191876320
# RWgrP 202131290
# 6pVH4 193832560
print(readNumber('M5Pr5.png'))
print(readNumber('RWgrP.png'))
print(readNumber('6pVH4.png'))
The related question is on that link Read text below barcode pytesseract python