import cv2
import pytesseract

pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'

# set the path of image
image_path = "Images/3.jpg"
  
image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.bilateralFilter(gray, 11,90, 90)

edges = cv2.Canny(blur, 30, 200)

cnts, new = cv2.findContours(edges.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
image_copy = image.copy()
_ = cv2.drawContours(image_copy, cnts, -1, (255,0,255),2)

cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:30]
image_copy = image.copy()
_ = cv2.drawContours(image_copy, cnts, -1, (255,0,255),2)

plate = None
for c in cnts:
    perimeter = cv2.arcLength(c, True)
    edges_count = cv2.approxPolyDP(c, 0.02 * perimeter, True)
    if len(edges_count) == 4:
        x,y,w,h = cv2.boundingRect(c)
        plate = image[y:y+h, x:x+w]
        break

# cv2.imshow("Blur_Image",blur)
# cv2.imshow("Edge_detected",edges)
# cv2.imshow("Contours",image_copy)
# cv2.imshow("Sorted_Cont ",image_copy)
# cv2.imshow("Final",plate)


def text_detection(plate):
    (thresh, img) = cv2.threshold(plate, 150, 180, cv2.THRESH_BINARY)
    text = pytesseract.image_to_string(img)
    # print(text)
    if len(text) is 0 or text[0] is '\n':
        output = False
    else:
        print("Vehicle Number:", end=" ")
        cv2.imshow("Final", plate)
        for i in range(len(text)):
            if 48 <= ord(text[i]) <= 57 or 65 <= ord(text[i]) <= 90 or 97 <= ord(text[i]) <= 122:
                print(text[i], end="")
        output = True
    return output


result = text_detection(plate)
# print(result)
if not result:
    text = input("Enter the vehicle number: ")
    print(text)

cv2.waitKey(0)

