from transform import four_point_transform
import imutils
import argparse
import cv2
import numpy as np
# gives the black and white feel to our scanned image
from skimage.filters import threshold_local

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True, help = "Path to the image to be scanned")
args = vars(ap.parse_args())


image = cv2.imread(args["image"])
original = image.copy()
original2 = image.copy()
ratio = image.shape[0] / 500.0
image = imutils.resize(image, height = 500)
image = imutils.rotate(image, 90)
original = imutils.rotate(original, 90)


gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# a bilateral filter could also be used, it better preserves the edges but here its not a big deal
# because we will simply have only the document in our image.
gray = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(gray, 75, 200)


print("STEP 1: Edge Detection")
cv2.imshow("Image", image)
cv2.imshow("Edged", edged)
cv2.waitKey(0)
cv2.destroyAllWindows()

(_, cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]

for c in cnts:


	peri = cv2.arcLength(c, True)
	approx = cv2.approxPolyDP(c, 0.02 * peri, True)

	if len(approx) == 4:
		screenCnt = approx
		break

print("STEP 2: Find Contours of paper")
cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)
cv2.imshow("Outline" , image)
cv2.waitKey(0)
cv2.destroyAllWindows()

# apply the four point transform feeding in the list of end points scaled to the correct ratio
warped = four_point_transform(original, screenCnt.reshape(4,2)  * ratio	)

warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)

# not sure about the parameters
T = threshold_local(warped, 11, offset = 10, method = "gaussian")

warped = (warped > T).astype("uint8") * 255

# show the original and scanned images.
print("STEP 3: Apply perspective transform")
cv2.imshow("Original", imutils.resize(original2, height = 650))
cv2.imshow("Scanned", imutils.resize(warped, height = 650))

cv2.waitKey(0)



