import cv2
import numpy as np

# define a video capture object
vid = cv2.VideoCapture(0)

while(True):

    # Capture the video frame
    # by frame
    ret, frame = vid.read()

    # Convert to grayscale.
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    gray_blurred = cv2.blur(gray, (3, 3))

    ret, thresh = cv2.threshold(gray_blurred, 50,255,00)
    contours, hierarchy = cv2.findContours(thresh, 1, 2)

    if contours is not None:
        for cnt in contours:
            #x1,y1 = cnt[0][0]
            approx = cv2.approxPolyDP(cnt, 0.1*cv2.arcLength(cnt, True), True)
            if len(approx) == 4:
                x, y, w, h = cv2.boundingRect(approx)
                if (w > 40):
                    if (w < 200):
                        rect = cv2.minAreaRect(approx)
                        box = cv2.boxPoints(rect)
                        box = np.intp(box)
                        frame = cv2.drawContours(frame,[box],0,(0,0,255),2)

    # Display the resulting frame
    cv2.imshow('frame', frame)
    #cv2.imshow('frame', thresh)

    # the 'q' button is set as the
    # quitting button you may use any
    # desired button of your choice
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# After the loop release the cap object
vid.release()
# Destroy all the windows
cv2.destroyAllWindows()
