#! /usr/bin/env python # -*- coding: utf-8 -*- # # QReader # Copyright (C) 2011, 2012, Alan Aguiar # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # Contact information: # Alan Aguiar import pygame import pygame.camera import gtk #import subprocess import os import time #import shutil #import hashlib import zbar #import Image import re #from codecs import BOM_UTF8 from gettext import gettext as _ class Captura(object): def __init__(self, tamanio): self.string_captura = '' # creamos una superfcie para usarla de pantalla #self.pantalla = pygame.display.get_surface() self.pantalla = pygame.display.set_mode((1200,900)) print dir(pygame.display) # creamos una superficie para la captura self.captura = pygame.surface.Surface(tamanio, 0, self.pantalla) # inicializamos el modulo pygame de la camara pygame.camera.init() # inicializo en None la cámara self.cam = None # obtenemos la lista de camaras self.lcamaras = pygame.camera.list_cameras() # si no hay ninguna camara if self.lcamaras: # creamos la camara, con tamanio y modo color RGB self.cam = pygame.camera.Camera(self.lcamaras[0], tamanio, 'RGB') try: # seteamos flip en horizontal, vertical false self.cam.set_controls(True, False) # iniciamos la camara self.cam.start() # obtengo el estado res = self.cam.get_controls() # guardo si el flip lo hace la cámara self.flip = res[0] except: print _('Error en la inicialización de la cámara') else: # mandamos el error correspondiente print _('No se encontro ninguna camara.') def obtener_captura(self): self.string_captura = '' # guardamos una captura self.captura = self.cam.get_image(self.captura) # si el flip no lo hace la cámara if not(self.flip): # giro la captura en el horizontal self.captura = pygame.transform.flip(self.captura,True,False) # recuadro #subsurface(Rect) -> Surface self.chica = self.captura.subsurface((170,90,300,300)) #print self.chica.get_height() self.string_captura = pygame.image.tostring(self.chica, 'P') #print self.captura.get_height() #print self.captura.get_width() def mostrar_captura(self): # escalo la captura para mostrar self.captura2 = pygame.transform.scale(self.captura, (640,480)) self.pantalla.fill((84,185,72)) # muestro la captura en pantalla self.pantalla.blit(self.captura2, (0,0)) # rellenamos la esquina superior con el color calibrado # recuadramos el color para resaltarlo rect = pygame.draw.rect(self.captura2, (0,0,0), (170,90,304,304), 4) self.pantalla.blit(self.captura2, (0,0)) def limpiar(self): # relleno la pantalla con un color homogeneo self.pantalla.fill((84, 185, 72)) class QR(object): data_decode = { 'text': lambda data: data, 'url': lambda data: data, 'email': lambda data: data.replace(u"mailto:",u"").replace(u"MAILTO:",u""), 'emailmessage': lambda data: re.findall(u"MATMSG:TO:(.*);SUB:(.*);BODY:(.*);;", data, re.IGNORECASE)[0], 'telephone': lambda data: data.replace(u"tel:",u"").replace(u"TEL:",u""), 'sms': lambda data: re.findall(u"SMSTO:(.*):(.*)", data, re.IGNORECASE)[0], 'mms': lambda data: re.findall(u"MMSTO:(.*):(.*)", data, re.IGNORECASE)[0], 'geo': lambda data: re.findall(u"GEO:(.*),(.*)", data, re.IGNORECASE)[0], 'bookmark': lambda data: re.findall(u"MEBKM:TITLE:(.*);URL:(.*);;", data, re.IGNORECASE)[0], 'phonebook': lambda data: dict(re.findall("(.*?):(.*?);", data.replace("MECARD:",""), re.IGNORECASE)) } def data_recognise(self, data = None): """Returns an unicode string indicating the data type of the data paramater""" data = data or self.data data_lower = data.lower() if data_lower.startswith(u"http://") or data_lower.startswith(u"https://"): return u'url' elif data_lower.startswith(u"mailto:"): return u'email' elif data_lower.startswith(u"matmsg:to:"): return u'emailmessage' elif data_lower.startswith(u"tel:"): return u'telephone' elif data_lower.startswith(u"smsto:"): return u'sms' elif data_lower.startswith(u"mmsto:"): return u'mms' elif data_lower.startswith(u"geo:"): return u'geo' elif data_lower.startswith(u"mebkm:title:"): return u'bookmark' elif data_lower.startswith(u"mecard:"): return u'phonebook' else: return u'text' def __init__( self, data=u'NULL', pixel_size=3, level='L', margin_size=4, data_type=u'text', filename=None ): self.pixel_size = pixel_size self.level = level self.margin_size = margin_size self.data_type = data_type #you should pass data as a unicode object or a list/tuple of unicode objects. self.data = data #get a temp directory self.directory = os.path.join('/tmp', 'qr-%f' % time.time()) self.filename = filename os.makedirs(self.directory) self.scanner = zbar.ImageScanner() # configure the reader self.scanner.parse_config('enable') def decode2(self, string): #image = zbar.Image(300, 300, 'Y800', string) image = zbar.Image(300, 300, 'GREY', string) print 'alan', image.format # scan the image for barcodes result = self.scanner.scan(image) # extract results if result == False: return False else: for symbol in image: # clean up #Assuming data is encoded in utf8 self.data = symbol.data.decode(u'utf-8') self.data_type = self.data_recognise() del(image) image = None return True class QReader: def __init__(self, parent): # guardo referencia al padre self.parent = parent # para manejar la tasa de refresco self.clock = pygame.time.Clock() def run(self): decoder = QR() # establezco un tamaño incial self.tamanioi = (960.0, 720.0) # por defecto se muestra la captura self.mostrar = True # creamos una captura, inicializamos la camara self.c = Captura((640, 480)) pygame.init() # mientras True while True: # Pump GTK messages. while gtk.events_pending(): gtk.main_iteration() # Pump PyGame messages. for event in pygame.event.get(): if event.type == pygame.QUIT: # salgo return elif event.type == pygame.VIDEORESIZE: pygame.display.set_mode(event.size, pygame.RESIZABLE) self.c.obtener_captura() print decoder.decode2(self.c.string_captura) print 'tipo: ', decoder.data_type print 'datos', decoder.data self.c.mostrar_captura() # actualizo la pantalla pygame.display.flip() # seteo a 10 CPS (CuadrosPorSegundo) self.clock.tick(10) if __name__ == "__main__": q = QReader(None) q.run()