-
Notifications
You must be signed in to change notification settings - Fork 709
/
camera_view.dart
384 lines (357 loc) · 12.3 KB
/
camera_view.dart
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_mlkit_commons/google_mlkit_commons.dart';
class CameraView extends StatefulWidget {
CameraView(
{Key? key,
required this.customPaint,
required this.onImage,
this.onCameraFeedReady,
this.onDetectorViewModeChanged,
this.onCameraLensDirectionChanged,
this.initialCameraLensDirection = CameraLensDirection.back})
: super(key: key);
final CustomPaint? customPaint;
final Function(InputImage inputImage) onImage;
final VoidCallback? onCameraFeedReady;
final VoidCallback? onDetectorViewModeChanged;
final Function(CameraLensDirection direction)? onCameraLensDirectionChanged;
final CameraLensDirection initialCameraLensDirection;
@override
State<CameraView> createState() => _CameraViewState();
}
class _CameraViewState extends State<CameraView> {
static List<CameraDescription> _cameras = [];
CameraController? _controller;
int _cameraIndex = -1;
double _currentZoomLevel = 1.0;
double _minAvailableZoom = 1.0;
double _maxAvailableZoom = 1.0;
double _minAvailableExposureOffset = 0.0;
double _maxAvailableExposureOffset = 0.0;
double _currentExposureOffset = 0.0;
bool _changingCameraLens = false;
@override
void initState() {
super.initState();
_initialize();
}
void _initialize() async {
if (_cameras.isEmpty) {
_cameras = await availableCameras();
}
for (var i = 0; i < _cameras.length; i++) {
if (_cameras[i].lensDirection == widget.initialCameraLensDirection) {
_cameraIndex = i;
break;
}
}
if (_cameraIndex != -1) {
_startLiveFeed();
}
}
@override
void dispose() {
_stopLiveFeed();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(body: _liveFeedBody());
}
Widget _liveFeedBody() {
if (_cameras.isEmpty) return Container();
if (_controller == null) return Container();
if (_controller?.value.isInitialized == false) return Container();
return ColoredBox(
color: Colors.black,
child: Stack(
fit: StackFit.expand,
children: <Widget>[
Center(
child: _changingCameraLens
? Center(
child: const Text('Changing camera lens'),
)
: CameraPreview(
_controller!,
child: widget.customPaint,
),
),
_backButton(),
_switchLiveCameraToggle(),
_detectionViewModeToggle(),
_zoomControl(),
_exposureControl(),
],
),
);
}
Widget _backButton() => Positioned(
top: 40,
left: 8,
child: SizedBox(
height: 50.0,
width: 50.0,
child: FloatingActionButton(
heroTag: Object(),
onPressed: () => Navigator.of(context).pop(),
backgroundColor: Colors.black54,
child: Icon(
Icons.arrow_back_ios_outlined,
size: 20,
),
),
),
);
Widget _detectionViewModeToggle() => Positioned(
bottom: 8,
left: 8,
child: SizedBox(
height: 50.0,
width: 50.0,
child: FloatingActionButton(
heroTag: Object(),
onPressed: widget.onDetectorViewModeChanged,
backgroundColor: Colors.black54,
child: Icon(
Icons.photo_library_outlined,
size: 25,
),
),
),
);
Widget _switchLiveCameraToggle() => Positioned(
bottom: 8,
right: 8,
child: SizedBox(
height: 50.0,
width: 50.0,
child: FloatingActionButton(
heroTag: Object(),
onPressed: _switchLiveCamera,
backgroundColor: Colors.black54,
child: Icon(
Platform.isIOS
? Icons.flip_camera_ios_outlined
: Icons.flip_camera_android_outlined,
size: 25,
),
),
),
);
Widget _zoomControl() => Positioned(
bottom: 16,
left: 0,
right: 0,
child: Align(
alignment: Alignment.bottomCenter,
child: SizedBox(
width: 250,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Slider(
value: _currentZoomLevel,
min: _minAvailableZoom,
max: _maxAvailableZoom,
activeColor: Colors.white,
inactiveColor: Colors.white30,
onChanged: (value) async {
setState(() {
_currentZoomLevel = value;
});
await _controller?.setZoomLevel(value);
},
),
),
Container(
width: 50,
decoration: BoxDecoration(
color: Colors.black54,
borderRadius: BorderRadius.circular(10.0),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Text(
'${_currentZoomLevel.toStringAsFixed(1)}x',
style: TextStyle(color: Colors.white),
),
),
),
),
],
),
),
),
);
Widget _exposureControl() => Positioned(
top: 40,
right: 8,
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: 250,
),
child: Column(children: [
Container(
width: 55,
decoration: BoxDecoration(
color: Colors.black54,
borderRadius: BorderRadius.circular(10.0),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Text(
'${_currentExposureOffset.toStringAsFixed(1)}x',
style: TextStyle(color: Colors.white),
),
),
),
),
Expanded(
child: RotatedBox(
quarterTurns: 3,
child: SizedBox(
height: 30,
child: Slider(
value: _currentExposureOffset,
min: _minAvailableExposureOffset,
max: _maxAvailableExposureOffset,
activeColor: Colors.white,
inactiveColor: Colors.white30,
onChanged: (value) async {
setState(() {
_currentExposureOffset = value;
});
await _controller?.setExposureOffset(value);
},
),
),
),
)
]),
),
);
Future _startLiveFeed() async {
final camera = _cameras[_cameraIndex];
_controller = CameraController(
camera,
// Set to ResolutionPreset.high. Do NOT set it to ResolutionPreset.max because for some phones does NOT work.
ResolutionPreset.high,
enableAudio: false,
imageFormatGroup: Platform.isAndroid
? ImageFormatGroup.nv21
: ImageFormatGroup.bgra8888,
);
_controller?.initialize().then((_) {
if (!mounted) {
return;
}
_controller?.getMinZoomLevel().then((value) {
_currentZoomLevel = value;
_minAvailableZoom = value;
});
_controller?.getMaxZoomLevel().then((value) {
_maxAvailableZoom = value;
});
_currentExposureOffset = 0.0;
_controller?.getMinExposureOffset().then((value) {
_minAvailableExposureOffset = value;
});
_controller?.getMaxExposureOffset().then((value) {
_maxAvailableExposureOffset = value;
});
_controller?.startImageStream(_processCameraImage).then((value) {
if (widget.onCameraFeedReady != null) {
widget.onCameraFeedReady!();
}
if (widget.onCameraLensDirectionChanged != null) {
widget.onCameraLensDirectionChanged!(camera.lensDirection);
}
});
setState(() {});
});
}
Future _stopLiveFeed() async {
await _controller?.stopImageStream();
await _controller?.dispose();
_controller = null;
}
Future _switchLiveCamera() async {
setState(() => _changingCameraLens = true);
_cameraIndex = (_cameraIndex + 1) % _cameras.length;
await _stopLiveFeed();
await _startLiveFeed();
setState(() => _changingCameraLens = false);
}
void _processCameraImage(CameraImage image) {
final inputImage = _inputImageFromCameraImage(image);
if (inputImage == null) return;
widget.onImage(inputImage);
}
final _orientations = {
DeviceOrientation.portraitUp: 0,
DeviceOrientation.landscapeLeft: 90,
DeviceOrientation.portraitDown: 180,
DeviceOrientation.landscapeRight: 270,
};
InputImage? _inputImageFromCameraImage(CameraImage image) {
if (_controller == null) return null;
// get image rotation
// it is used in android to convert the InputImage from Dart to Java: https://github.com/flutter-ml/google_ml_kit_flutter/blob/master/packages/google_mlkit_commons/android/src/main/java/com/google_mlkit_commons/InputImageConverter.java
// `rotation` is not used in iOS to convert the InputImage from Dart to Obj-C: https://github.com/flutter-ml/google_ml_kit_flutter/blob/master/packages/google_mlkit_commons/ios/Classes/MLKVisionImage%2BFlutterPlugin.m
// in both platforms `rotation` and `camera.lensDirection` can be used to compensate `x` and `y` coordinates on a canvas: https://github.com/flutter-ml/google_ml_kit_flutter/blob/master/packages/example/lib/vision_detector_views/painters/coordinates_translator.dart
final camera = _cameras[_cameraIndex];
final sensorOrientation = camera.sensorOrientation;
// print(
// 'lensDirection: ${camera.lensDirection}, sensorOrientation: $sensorOrientation, ${_controller?.value.deviceOrientation} ${_controller?.value.lockedCaptureOrientation} ${_controller?.value.isCaptureOrientationLocked}');
InputImageRotation? rotation;
if (Platform.isIOS) {
rotation = InputImageRotationValue.fromRawValue(sensorOrientation);
} else if (Platform.isAndroid) {
var rotationCompensation =
_orientations[_controller!.value.deviceOrientation];
if (rotationCompensation == null) return null;
if (camera.lensDirection == CameraLensDirection.front) {
// front-facing
rotationCompensation = (sensorOrientation + rotationCompensation) % 360;
} else {
// back-facing
rotationCompensation =
(sensorOrientation - rotationCompensation + 360) % 360;
}
rotation = InputImageRotationValue.fromRawValue(rotationCompensation);
// print('rotationCompensation: $rotationCompensation');
}
if (rotation == null) return null;
// print('final rotation: $rotation');
// get image format
final format = InputImageFormatValue.fromRawValue(image.format.raw);
// validate format depending on platform
// only supported formats:
// * nv21 for Android
// * bgra8888 for iOS
if (format == null ||
(Platform.isAndroid && format != InputImageFormat.nv21) ||
(Platform.isIOS && format != InputImageFormat.bgra8888)) return null;
// since format is constraint to nv21 or bgra8888, both only have one plane
if (image.planes.length != 1) return null;
final plane = image.planes.first;
// compose InputImage using bytes
return InputImage.fromBytes(
bytes: plane.bytes,
metadata: InputImageMetadata(
size: Size(image.width.toDouble(), image.height.toDouble()),
rotation: rotation, // used only in Android
format: format, // used only in iOS
bytesPerRow: plane.bytesPerRow, // used only in iOS
),
);
}
}