-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathmain.py
337 lines (264 loc) · 10.8 KB
/
main.py
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
'''
Qrcode example application
==========================
Author: Mathieu Virbel <[email protected]>
Featuring:
- Android camera initialization
- Show the android camera into a Android surface that act as an overlay
- New AndroidWidgetHolder that control any android view as an overlay
- New ZbarQrcodeDetector that use AndroidCamera / PreviewFrame + zbar to
detect Qrcode.
'''
__version__ = '1.0'
from collections import namedtuple
from kivy.lang import Builder
from kivy.app import App
from kivy.properties import ObjectProperty, ListProperty, BooleanProperty, \
NumericProperty
from kivy.uix.widget import Widget
from kivy.uix.anchorlayout import AnchorLayout
from kivy.graphics import Color, Line
from jnius import autoclass, PythonJavaClass, java_method, cast
from android.runnable import run_on_ui_thread
# preload java classes
System = autoclass('java.lang.System')
System.loadLibrary('iconv')
PythonActivity = autoclass('org.renpy.android.PythonActivity')
Camera = autoclass('android.hardware.Camera')
ImageScanner = autoclass('net.sourceforge.zbar.ImageScanner')
Config = autoclass('net.sourceforge.zbar.Config')
SurfaceView = autoclass('android.view.SurfaceView')
LayoutParams = autoclass('android.view.ViewGroup$LayoutParams')
Image = autoclass('net.sourceforge.zbar.Image')
ImageFormat = autoclass('android.graphics.ImageFormat')
LinearLayout = autoclass('android.widget.LinearLayout')
Symbol = autoclass('net.sourceforge.zbar.Symbol')
class PreviewCallback(PythonJavaClass):
'''Interface used to get back the preview frame of the Android Camera
'''
__javainterfaces__ = ('android.hardware.Camera$PreviewCallback', )
def __init__(self, callback):
super(PreviewCallback, self).__init__()
self.callback = callback
@java_method('([BLandroid/hardware/Camera;)V')
def onPreviewFrame(self, data, camera):
self.callback(camera, data)
class SurfaceHolderCallback(PythonJavaClass):
'''Interface used to know exactly when the Surface used for the Android
Camera will be created and changed.
'''
__javainterfaces__ = ('android.view.SurfaceHolder$Callback', )
def __init__(self, callback):
super(SurfaceHolderCallback, self).__init__()
self.callback = callback
@java_method('(Landroid/view/SurfaceHolder;III)V')
def surfaceChanged(self, surface, fmt, width, height):
self.callback(fmt, width, height)
@java_method('(Landroid/view/SurfaceHolder;)V')
def surfaceCreated(self, surface):
pass
@java_method('(Landroid/view/SurfaceHolder;)V')
def surfaceDestroyed(self, surface):
pass
class AndroidWidgetHolder(Widget):
'''Act as a placeholder for an Android widget.
It will automatically add / remove the android view depending if the widget
view is set or not. The android view will act as an overlay, so any graphics
instruction in this area will be covered by the overlay.
'''
view = ObjectProperty(allownone=True)
'''Must be an Android View
'''
def __init__(self, **kwargs):
self._old_view = None
from kivy.core.window import Window
self._window = Window
kwargs['size_hint'] = (None, None)
super(AndroidWidgetHolder, self).__init__(**kwargs)
def on_view(self, instance, view):
if self._old_view is not None:
layout = cast(LinearLayout, self._old_view.getParent())
layout.removeView(self._old_view)
self._old_view = None
if view is None:
return
activity = PythonActivity.mActivity
activity.addContentView(view, LayoutParams(*self.size))
view.setZOrderOnTop(True)
view.setX(self.x)
view.setY(self._window.height - self.y - self.height)
self._old_view = view
def on_size(self, instance, size):
if self.view:
params = self.view.getLayoutParams()
params.width = self.width
params.height = self.height
self.view.setLayoutParams(params)
self.view.setY(self._window.height - self.y - self.height)
def on_x(self, instance, x):
if self.view:
self.view.setX(x)
def on_y(self, instance, y):
if self.view:
self.view.setY(self._window.height - self.y - self.height)
class AndroidCamera(Widget):
'''Widget for controling an Android Camera.
'''
index = NumericProperty(0)
__events__ = ('on_preview_frame', )
def __init__(self, **kwargs):
self._holder = None
self._android_camera = None
super(AndroidCamera, self).__init__(**kwargs)
self._holder = AndroidWidgetHolder(size=self.size, pos=self.pos)
self.add_widget(self._holder)
@run_on_ui_thread
def stop(self):
if self._android_camera is None:
return
self._android_camera.setPreviewCallback(None)
self._android_camera.release()
self._android_camera = None
self._holder.view = None
@run_on_ui_thread
def start(self):
if self._android_camera is not None:
return
self._android_camera = Camera.open(self.index)
# create a fake surfaceview to get the previewCallback working.
self._android_surface = SurfaceView(PythonActivity.mActivity)
surface_holder = self._android_surface.getHolder()
# create our own surface holder to correctly call the next method when
# the surface is ready
self._android_surface_cb = SurfaceHolderCallback(self._on_surface_changed)
surface_holder.addCallback(self._android_surface_cb)
# attach the android surfaceview to our android widget holder
self._holder.view = self._android_surface
def _on_surface_changed(self, fmt, width, height):
# internal, called when the android SurfaceView is ready
# FIXME if the size is not handled by the camera, it will failed.
params = self._android_camera.getParameters()
params.setPreviewSize(width, height)
self._android_camera.setParameters(params)
# now that we know the camera size, we'll create 2 buffers for faster
# result (using Callback buffer approach, as described in Camera android
# documentation)
# it also reduce the GC collection
bpp = ImageFormat.getBitsPerPixel(params.getPreviewFormat()) / 8.
buf = '\x00' * int(width * height * bpp)
self._android_camera.addCallbackBuffer(buf)
self._android_camera.addCallbackBuffer(buf)
# create a PreviewCallback to get back the onPreviewFrame into python
self._previewCallback = PreviewCallback(self._on_preview_frame)
# connect everything and start the preview
self._android_camera.setPreviewCallbackWithBuffer(self._previewCallback);
self._android_camera.setPreviewDisplay(self._android_surface.getHolder())
self._android_camera.startPreview();
def _on_preview_frame(self, camera, data):
# internal, called by the PreviewCallback when onPreviewFrame is
# received
self.dispatch('on_preview_frame', camera, data)
# reintroduce the data buffer into the queue
self._android_camera.addCallbackBuffer(data)
def on_preview_frame(self, camera, data):
pass
def on_size(self, instance, size):
if self._holder:
self._holder.size = size
def on_pos(self, instance, pos):
if self._holder:
self._holder.pos = pos
class ZbarQrcodeDetector(AnchorLayout):
'''Widget that use the AndroidCamera and zbar to detect qrcode.
When found, the `symbols` will be updated
'''
camera_size = ListProperty([320, 240])
symbols = ListProperty([])
# XXX can't work now, due to overlay.
show_bounds = BooleanProperty(False)
Qrcode = namedtuple('Qrcode',
['type', 'data', 'bounds', 'quality', 'count'])
def __init__(self, **kwargs):
super(ZbarQrcodeDetector, self).__init__(**kwargs)
self._camera = AndroidCamera(
size=self.camera_size,
size_hint=(None, None))
self._camera.bind(on_preview_frame=self._detect_qrcode_frame)
self.add_widget(self._camera)
# create a scanner used for detecting qrcode
self._scanner = ImageScanner()
self._scanner.setConfig(0, Config.ENABLE, 0)
self._scanner.setConfig(Symbol.QRCODE, Config.ENABLE, 1)
self._scanner.setConfig(0, Config.X_DENSITY, 3)
self._scanner.setConfig(0, Config.Y_DENSITY, 3)
def start(self):
self._camera.start()
def stop(self):
self._camera.stop()
def _detect_qrcode_frame(self, instance, camera, data):
# the image we got by default from a camera is using the NV21 format
# zbar only allow Y800/GREY image, so we first need to convert,
# then start the detection on the image
parameters = camera.getParameters()
size = parameters.getPreviewSize()
barcode = Image(size.width, size.height, 'NV21')
barcode.setData(data)
barcode = barcode.convert('Y800')
result = self._scanner.scanImage(barcode)
if result == 0:
self.symbols = []
return
# we detected qrcode! extract and dispatch them
symbols = []
it = barcode.getSymbols().iterator()
while it.hasNext():
symbol = it.next()
qrcode = ZbarQrcodeDetector.Qrcode(
type=symbol.getType(),
data=symbol.getData(),
quality=symbol.getQuality(),
count=symbol.getCount(),
bounds=symbol.getBounds())
symbols.append(qrcode)
self.symbols = symbols
'''
# can't work, due to the overlay.
def on_symbols(self, instance, value):
if self.show_bounds:
self.update_bounds()
def update_bounds(self):
self.canvas.after.remove_group('bounds')
if not self.symbols:
return
with self.canvas.after:
Color(1, 0, 0, group='bounds')
for symbol in self.symbols:
x, y, w, h = symbol.bounds
x = self._camera.right - x - w
y = self._camera.top - y - h
Line(rectangle=[x, y, w, h], group='bounds')
'''
if __name__ == '__main__':
qrcode_kv = '''
BoxLayout:
orientation: 'vertical'
ZbarQrcodeDetector:
id: detector
Label:
text: '\\n'.join(map(repr, detector.symbols))
size_hint_y: None
height: '100dp'
BoxLayout:
size_hint_y: None
height: '48dp'
Button:
text: 'Scan a qrcode'
on_release: detector.start()
Button:
text: 'Stop detection'
on_release: detector.stop()
'''
class QrcodeExample(App):
def build(self):
return Builder.load_string(qrcode_kv)
QrcodeExample().run()