1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
|
#! /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 <http://www.gnu.org/licenses/>.
#
# Contact information:
# Alan Aguiar <alanjas@gmail.com>
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()
# 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')
# obtengo la resolución de la cámara
res = self.cam.get_size()
# si no es 320, 240 (Sugar nuevo)
if not (res == tamanio):
tamanio = (352, 288)
# inicializo en 352, 288
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):
# 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((0,0,120,120))
print self.chica.get_height()
self.string_captura = pygame.image.tostring(self.captura, 'RGB')
#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.pantalla, (0,0,0), (0,0,120,120), 4)
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(640, 480, 'Y800', string)
# scan the image for barcodes
result = self.scanner.scan(image)
# extract results
if result == 0:
return False
else:
for symbol in image:
pass
# clean up
del(image)
#Assuming data is encoded in utf8
self.data = symbol.data.decode(u'utf-8')
self.data_type = self.data_recognise()
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))
# 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()
decoder.decode2(self.c.string_captura)
print decoder.data
self.c.mostrar_captura()
# actualizo la pantalla
pygame.display.flip()
# seteo a 10 CPS (CuadrosPorSegundo)
self.clock.tick(10)
|