# IPython Notebook code
import sys
import cv2
import cv
import numpy as np
import matplotlib.pyplot as plt
import urllib
from lxml import html
import requests
#%matplotlib inline

ROOT = 'http://jurnalul.ro'

def acquire_image():
    filename = 'capture.jpg'
    # Get URL
    page = requests.get('http://jurnalul.ro/webcam/lascar-catargiu-268.html')
    tree = html.fromstring(page.text)
    url = tree.xpath('//*[@id="webcam_img"]')[0].xpath('attribute::src')[0]
    print url
    urllib.urlretrieve(ROOT+url, filename)
    # TODO: sterge asta
    filename = 'buc_cam6.png'
    return filename

# Detects the number of vehicles present in an image
def get_vehicle_count(filename):
    DEFAULT_WIDTH = 600
    DEFAULT_HEIGHT = 600

    # cctv_image = cv2.imread('ny_cam.png')
    try:
        cctv_image = cv.LoadImage(filename)
    except IOError:
        print "Error reading image file."
        exit(-1)

    cctv_mat = np.asarray(cctv_image[:,:])

    if cctv_image.width > DEFAULT_WIDTH | cctv_image.height > DEFAULT_HEIGHT:
        # compute the factor at which to scale the image
        scale = max(cctv_image.width/DEFAULT_WIDTH,cctv_image.height/DEFAULT_HEIGHT)
        new_size = (cctv_image.width/scale, cctv_image.height/scale)

        # resize the image
        cctv_image_resized = cv2.resize(cctv_mat, new_size, \
                interpolation=cv2.INTER_AREA)

        bitmap = cv.CreateImageHeader((cctv_image_resized.shape[1], \
                cctv_image_resized.shape[0]), cv.IPL_DEPTH_8U, 3)
        cv.SetData(bitmap, cctv_image_resized.tostring(),
                   cctv_image_resized.dtype.itemsize * 3 * cctv_image_resized.shape[1])

        sys.stdout.write("BEFORE %d %d\n" % (cctv_image.width, cctv_image.height))
        sys.stdout.write("AFTER %d %d\n" % (bitmap.width, bitmap.height))
        sys.stdout.flush()

        # get the array coresponding to the resized image
        cctv_mat = np.asarray(bitmap[:,:])

    # the 'cascade.xml' file is the file generated by the training script above
    vehicle_classifier = cv2.CascadeClassifier('cascade.xml')

    # various parameters can be passed to modify how objects are detected
    vehicles = vehicle_classifier.detectMultiScale(cctv_mat, 1.1, 100, \
            maxSize=(DEFAULT_WIDTH,DEFAULT_HEIGHT))

    print 'Vehicles detected: %d' % (len(vehicles))

    # Putem scapa de codul asta, ca oricum nu ne trebuie sa faca dreptunghiuri in
    # jurul lor
    # draw a rectangle around every vehicle detected
    for (x,y,w,h) in vehicles:
        cv2.rectangle(cctv_mat, (x,y), (x+w, y+h),(255,0,0),2)

    plt.figure(figsize=(9,9))
    plt.axis('off')
    plt.imshow(cv2.cvtColor(cctv_mat, cv2.COLOR_BGR2RGB))

if __name__ == "__main__":
    image = acquire_image()
    get_vehicle_count(image)
