import cv2
import numpy as np
import pytesseract
from PIL import Image
from pytesseract import image_to_string

print("Put a business card or another sheet with text in the visual range of your attached camera. Once placed correctly, press >d< on your keyboard to detect the text.")

cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame from attached webcam
    ret, frame = cap.read()

    # operations per frame
    # convert to gray
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
    # get rid of noise by using erosion and dilation
    kernel = np.ones((1, 1), np.uint8)
    gray = cv2.erode(gray, kernel, iterations=10)
    gray = cv2.dilate(gray, kernel, iterations=10)
    
    # Display the result
    cv2.imshow('frame',gray)
    
    # wait for keyboard input >d< to start text detection
    if cv2.waitKey(1) & 0xFF == ord('d'):
        result = pytesseract.image_to_string(gray)
        print(result)
    
    # wait for keyboard input >q< to quit application
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break


# release capture and terminate
cap.release()
cv2.destroyAllWindows()

