import cv2
import urllib
import numpy as np

class CAM(object):
	def __init__(self):
		self.stream=''
		self.bytes=''
		self.forma=''
	def init(self,direccion):
		if direccion[0:4]=="http" or direccion[0:4]=="HTTP":
			self.forma="IP"
			self.stream=urllib.urlopen(direccion)
		if direccion[0:7]=="/dev/vi":
			self.forma="DISP"
			self.stream=cv2.VideoCapture(int(direccion[-1]))
	def read(self):
		if self.forma=="DISP":
			ret,img=self.stream.read()
			return img
		if self.forma=="IP":
			while (True):		
				self.bytes+=self.stream.read(2048)
  				a=self.bytes.find('\xff\xd8')
  				b=self.bytes.find('\xff\xd9')

  				if a!=-1 and b!=-1:
    					jpg=self.bytes[a:b+2]
    					self.bytes=self.bytes[b+2:]
					i= cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.CV_LOAD_IMAGE_COLOR)
				
					break
		
			return i
