Пример #1
0
class Camara(object):
    def __init__(self):
        self.resolucion = (320, 240)
        self.frames = 10
        self.windows = False
        self.visible = False
        self.pantalla = ''
        self.camara = ''
        self.captura = ''
        self.captura_final = ''
        self.numero_imagen = 0
        self.pausa = 100
        self.loop = True
        self.log = self.log_default
        self.visible = False
        self.conectado = False
        self.timer = Timer()

    def config(self,
               Resolucion=(320, 240),
               Frames=10,
               Windows=False,
               Visible=False):
        self.resolucion = Resolucion
        self.frames = Frames
        self.windows = Windows
        self.visible = Visible

    def config_log(self, Log):
        #posibilidad de configurar clase Log(Texto, Modulo)
        self.log = Log.log

    def iniciar(self):
        self.__inicializar()
        self.__loop()

    def __inicializar(self):
        self.log("Iniciado Camara", "CAMARA")
        #INICIALIZAR CAMARA
        pygame.init()
        pygame.camera.init()
        #Modo Windows o Linux
        if self.windows:
            self.log("Usando Windows", "CAMARA")
            cameras = pygame.camera.list_cameras()
            self.log("Usando camera %s ..." % cameras[0], "VIDEO")
            #self.camara = pygame.camera.Camera(cameras[0],(640,480),"RGBA")
            self.camara = pygame.camera.Camera(cameras[0], self.resolucion,
                                               "RGBA")
        else:
            self.log("Usando Linux", "VIDEO")
            #self.camara = pygame.camera.Camera("/dev/video0", (640,480),"RGBA")
            self.camara = pygame.camera.Camera("/dev/video0", self.resolucion,
                                               "RGBA")
        #Iniciamos la camara
        self.camara.start()
        #mostramos en pantalla (si es necesario)
        if self.windows or self.visible:
            self.pantalla = pygame.display.set_mode(self.resolucion, 0)
            #self.captura  = pygame.surface.Surface((640,480), 0, self.pantalla)
            self.captura = pygame.surface.Surface(self.resolucion, 0,
                                                  self.pantalla)

    def __loop(self):
        self.log("Iniciado el loop de captura", "CAMARA")
        numero_imagen = 0
        self.timer.iniciar()
        while self.loop:
            self.__Capturar()
            self.__Almacenar()
            self.__Visualizar()
            self.__Interrupcion()

            delay = self.timer.delay(self.frames)
            pygame.time.delay(delay)
            tiempo = self.timer.fps()
            self.timer.iniciar()
            #print ("fps", tiempo)

    def __Capturar(self):
        # Si no esta conectado o no es visible no tiene sentido capturar
        if (self.conectado) or (self.visible):
            if self.windows:
                self.captura = self.camara.get_image(self.captura)
            else:
                # En linux podemos capturar la imagen sin un visualizador
                self.captura = self.camara.get_image()
                pass
            # Corregir en futuro si va a ser necesario la transformacion
            self.captura_final = pygame.transform.scale(
                self.captura, self.resolucion)

    def __Almacenar(self):
        # Grabamos imagenes si hay conexion
        if self.conectado == 1:
            nombre_imagen = "imagenes_tmp/img_tmp" + str(
                self.numero_imagen) + ".jpg"
            pygame.image.save(self.captura_final, nombre_imagen)
            #imagen guardada (incrementamos el contador)
            self.numero_imagen += 1
            if self.numero_imagen == 10:
                self.numero_imagen = 0

    def __Visualizar(self):
        # Mostramos imagen si esta visible
        if self.visible:
            self.pantalla.blit(self.captura_final, (0, 0))
            pygame.display.update()

    def __Interrupcion(self):
        # Interupcion
        if self.windows or self.visible:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.camara.stop()
                    pygame.quit()
                    self.loop = False
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        self.camara.stop()
                        pygame.quit()
                        self.loop = False

    def log_default(self, Texto, Modulo):
        print(Texto)
Пример #2
0
class Face_Comp(object):
    def __init__(self):
        self.tcp = Comunicacion()
        self.fdetect = Face_Detect2()
        self.th_detect = ThreadAdmin()
        self.host = ''
        self.port = ''
        self.ob_imagen = ''  # type: Imagen
        self.ob_label_fps = ''  # type: Label
        self.cola_imagen = queue.LifoQueue()
        self.conexion = False  # Estado de la conexion
        self.tiempo = Timer()
        self.evento_conexion = ''  # Evento que devuelve el estado de la conexion
        self.fun_envio = ''  # Evento para movimiento de la vista

    def config(self, host, puerto, ob_imagen, ob_label_fps, fun_envio):
        # type: (str, int, Imagen, Label, object)->None
        """ Se requiere IP del Servidor y Objeto Imagen
            Devuelve la imagen y los fps en un objeto label
            fun envio = fun(modulo, comando, valor)
        """
        self.host = host
        self.port = puerto
        self.ob_imagen = ob_imagen
        self.ob_label_fps = ob_label_fps
        self.tcp.config(host,
                        puerto,
                        binario=True,
                        callback=self.__call_conexion)
        self.fdetect.config(Callback_Imagen=self.__call_imagen)
        self.fdetect.config_callback(Func_Unica=self.__call_posdetect)
        self.fun_envio = fun_envio

    def config_eventos(self, evento_conexion=''):
        """evento_conexion: Funcion que devuelve True o False cuando conecta o desconecta
           Ej: def evento(Estado)
        """
        self.evento_conexion = evento_conexion

    def iniciar(self):
        self.tiempo.iniciar()
        self.tcp.iniciar()

    def desconectar(self):
        self.tcp.desconectar()
        self.th_detect.close()

    def __call_conexion(self, codigo, mensaje):
        """ recepcion de datos binarios del servidor tcp"""
        # Conectado
        if codigo == 2:
            self.conexion = True
            self.th_detect.start(self.__th_detector,
                                 '',
                                 'DETECTOR',
                                 enviar_ejecucion=True)
            self.evento_conexion(True)  # Devolvemos conectado
        # Desconecado
        elif codigo == 0:
            self.conexion = False
            self.evento_conexion(False)  # Devolvemos desconectado
        # Recepcion de datos
        elif codigo == 4:
            self.cola_imagen.put(mensaje)  # encolamos la imgen recibida
        # Errores
        elif codigo == -1:
            self.conexion = False
            self.evento_conexion(False)  # Devolvemos desconectado
        # Otros mensajes
        else:
            if codigo != 3:  # 3 es envio de mensajes
                print("MEN: " + str(codigo) + " " + str(mensaje))

    def __call_imagen(self, cv_imagen):
        """ recepcion de imagen procesada por el detector para insertar en el objeto imagen"""
        self.ob_imagen.imagen_cv(cv_imagen)

    def __th_detector(self, run):
        """ envia a analizar las imagenes que entran en cola """
        while run.value:
            if self.cola_imagen.qsize() > 0:
                # print(tiempo.fps())
                self.ob_label_fps.set_text("FPS: " +
                                           str(round(self.tiempo.fps(), 2)))
                imag = self.cola_imagen.get()
                self.fdetect.imagen(imag)
            time.sleep(0.01)

    def __call_posdetect(self, x, y):
        modulo = "FACE"
        comando = "CENTRAR"
        valor = str(x) + "/" + str(y)  # separador de valores /
        self.fun_envio(modulo, comando, valor)
Пример #3
0
# Esto es para poder hacer el from desde un nivel atras y funciona con launch.json
import os, sys
BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_PATH)

import time
from componentes.timer import Timer

tiempo = Timer()

tiempo.iniciar()

while True:
    #time.sleep(0.01)
    print("FPS: ", tiempo.fps())
    tiempo.delay(10)