import numpy as np
import cv2
import imutils
import pytesseract
import matplotlib.pyplot as plt
# %matplotlib inline
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

# Read the image file
image = cv2.imread('Car7.jpg')

def plot_image(img1, title1=""):     # define a function to plot image
    fig = plt.figure(figsize=[15,15])
    ax1 = fig.add_subplot(121)
    ax1.imshow(img1, cmap="gray")
    ax1.set(xticks=[], yticks=[], title=title1)

# Resize the image - change width to 500
image = imutils.resize(image, width=500)

# Display the original image
cv2.imshow('Original image',image)
cv2.waitKey(0)
cv2.destroyAllWindows()
#plot_image(image,"Orignal Image")

# RGB to Gray scale conversion
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# plot_image(gray,"Grayscale Conversion")
cv2.imshow('Grayscale Conversion',gray)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Noise removal with iterative bilateral filter(removes noise while preserving edges)
blur = cv2.bilateralFilter(gray, 11, 17, 17)
#plot_image(blur,"Blur Image")

cv2.imshow('Blur Image',blur)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Find Edges of the grayscale image
edged = cv2.Canny(gray, 170, 200)
#plot_image(edged,"Canny Edges")

cv2.imshow('Canny Edges',edged)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Find contours based on Edges
cnts, new  = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

print(len(cnts))

# Create copy of original image to draw all contours
img1 = image.copy()
cv2.drawContours(img1, cnts, -1, (0,255,0), 3)
#plot_image(img1,"All Contours")

cv2.imshow('All Contours',img1)
cv2.waitKey(0)
cv2.destroyAllWindows()


print(len(cnts))

#sort contours based on their area keeping minimum required area as '30' (anything smaller than this will not be considered)
cnts=sorted(cnts, key = cv2.contourArea, reverse = True)[:200]
NumberPlateCnt = None #we currently have no Number plate contour

# Top 30 Contours
img2 = image.copy()
cv2.drawContours(img2, cnts, -1, (0,255,0), 3)
#plot_image(img2,"Top 30 Contours")
cv2.imshow('Top 30 Contours',img2)
cv2.waitKey(0)
cv2.destroyAllWindows()


# loop over our contours to find the best possible approximate contour of number plate
count = 0
idx =7
for c in cnts:
        peri = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.02 * peri, True)
        if len(approx) == 4:  # Select the contour with 4 corners
            NumberPlateCnt = approx #This is our approx Number Plate Contour

            # Crop those contours and store it in Cropped Images folder
            x, y, w, h = cv2.boundingRect(c) #This will find out co-ord for plate
            new_img = gray[y:y + h, x:x + w] #Create new image
            cv2.imwrite('Number plate image.jpg', new_img) #Store new image
            idx+=1

            break

# Drawing the selected contour on the original image
print(NumberPlateCnt)
cv2.drawContours(image, [NumberPlateCnt], -1, (0,255,0), 3)
#plot_image(image,"Final Image With Number Plate Detected")
cv2.imshow('Final Image With Number Plate Detected',image)
cv2.waitKey(0)
cv2.destroyAllWindows()


crop_img=cv2.imread('contour image.jpg')
#plot_image(crop_img,"Cropped Image")
cv2.imshow('Cropped Image',crop_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Use tesseract to covert image into string
text = pytesseract.image_to_string('contour image.jpg', lang='eng')
print("Number is :", text)

