Files
korken_mosaic/lib/main.dart

536 lines
16 KiB
Dart

import 'dart:async';
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';
import 'package:image/image.dart' as img;
import 'package:image_picker/image_picker.dart';
void main() {
runApp(const KorkenMosaicApp());
}
class KorkenMosaicApp extends StatelessWidget {
const KorkenMosaicApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Korken Mosaic',
theme: ThemeData(colorSchemeSeed: Colors.teal, useMaterial3: true),
home: const MosaicHomePage(),
);
}
}
class MosaicHomePage extends StatefulWidget {
const MosaicHomePage({super.key});
@override
State<MosaicHomePage> createState() => _MosaicHomePageState();
}
class _MosaicHomePageState extends State<MosaicHomePage> {
final ImagePicker _picker = ImagePicker();
final TextEditingController _gridWidthCtrl =
TextEditingController(text: '40');
final TextEditingController _gridHeightCtrl =
TextEditingController(text: '30');
final TextEditingController _capSizeCtrl = TextEditingController(text: '12');
Uint8List? _sourceImageBytes;
MosaicResult? _result;
bool _useCapSize = false;
bool _isGenerating = false;
Timer? _debounceTimer;
int _generationToken = 0;
final List<CapColor> _palette = [
CapColor(name: 'White', color: const Color(0xFFF2F2F2)),
CapColor(name: 'Black', color: const Color(0xFF222222)),
CapColor(name: 'Red', color: const Color(0xFFD84343)),
CapColor(name: 'Blue', color: const Color(0xFF3F6FD8)),
CapColor(name: 'Green', color: const Color(0xFF4FAE63)),
];
@override
void initState() {
super.initState();
_gridWidthCtrl.addListener(_scheduleRegenerate);
_gridHeightCtrl.addListener(_scheduleRegenerate);
_capSizeCtrl.addListener(_scheduleRegenerate);
}
@override
void dispose() {
_debounceTimer?.cancel();
_gridWidthCtrl.dispose();
_gridHeightCtrl.dispose();
_capSizeCtrl.dispose();
super.dispose();
}
Future<void> _pickImage() async {
final XFile? picked = await _picker.pickImage(source: ImageSource.gallery);
if (picked == null) return;
final bytes = await picked.readAsBytes();
setState(() {
_sourceImageBytes = bytes;
_result = null;
});
}
void _scheduleRegenerate() {
if (_sourceImageBytes == null || _result == null) return;
_debounceTimer?.cancel();
_debounceTimer = Timer(const Duration(milliseconds: 300), _generate);
}
void _addCapDialog() {
Color selected = Colors.orange;
final nameCtrl = TextEditingController();
final hexCtrl = TextEditingController(
text:
'#${selected.toARGB32().toRadixString(16).substring(2).toUpperCase()}',
);
showDialog<void>(
context: context,
builder: (ctx) {
return AlertDialog(
title: const Text('Add Bottle Cap Color'),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: nameCtrl,
decoration: const InputDecoration(labelText: 'Name'),
),
const SizedBox(height: 8),
TextField(
controller: hexCtrl,
decoration: const InputDecoration(labelText: 'Hex (#RRGGBB)'),
onChanged: (value) {
final parsed = _parseHex(value);
if (parsed != null) selected = parsed;
},
),
const SizedBox(height: 12),
ColorPicker(
pickerColor: selected,
onColorChanged: (c) {
selected = c;
hexCtrl.text =
'#${c.toARGB32().toRadixString(16).substring(2).toUpperCase()}';
},
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () {
final name = nameCtrl.text.trim();
if (name.isEmpty) return;
setState(() {
_palette.add(
CapColor(
name: name, color: _parseHex(hexCtrl.text) ?? selected),
);
});
Navigator.pop(ctx);
_scheduleRegenerate();
},
child: const Text('Add'),
),
],
);
},
);
}
Future<void> _generate() async {
if (_sourceImageBytes == null || _palette.isEmpty) return;
final int gridW = math.max(1, int.tryParse(_gridWidthCtrl.text) ?? 40);
final int gridH = math.max(1, int.tryParse(_gridHeightCtrl.text) ?? 30);
final int capSize = math.max(1, int.tryParse(_capSizeCtrl.text) ?? 12);
final token = ++_generationToken;
setState(() => _isGenerating = true);
final payload = <String, dynamic>{
'source': _sourceImageBytes!,
'useCapSize': _useCapSize,
'gridW': gridW,
'gridH': gridH,
'capSize': capSize,
'palette': _palette
.map((p) =>
<String, dynamic>{'name': p.name, 'value': p.color.toARGB32()})
.toList(growable: false),
};
final out = await compute(_generateMosaicIsolate, payload);
if (!mounted || token != _generationToken) return;
final palette = (out['palette'] as List)
.map(
(e) => CapColor(
name: e['name'] as String, color: Color(e['value'] as int)),
)
.toList(growable: false);
final countsList = (out['counts'] as List).cast<int>();
final counts = <CapColor, int>{};
for (int i = 0; i < palette.length; i++) {
counts[palette[i]] = countsList[i];
}
final sortedCounts = counts.entries.toList()
..sort((a, b) => b.value.compareTo(a.value));
setState(() {
_result = MosaicResult(
width: out['width'] as int,
height: out['height'] as int,
assignments: (out['assignments'] as List).cast<int>(),
palette: palette,
counts: counts,
sortedCounts: sortedCounts,
previewPng: out['previewPng'] as Uint8List,
);
_isGenerating = false;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Bottle-Cap Mosaic Prototype')),
floatingActionButton: FloatingActionButton.extended(
onPressed: _isGenerating ? null : _generate,
icon: _isGenerating
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.auto_fix_high),
label: Text(_isGenerating ? 'Generating…' : 'Generate Mosaic'),
),
body: Padding(
padding: const EdgeInsets.all(12),
child: ListView(
children: [
Wrap(
runSpacing: 8,
spacing: 8,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
FilledButton.icon(
onPressed: _pickImage,
icon: const Icon(Icons.image_outlined),
label: const Text('Import target image'),
),
if (_sourceImageBytes != null) const Text('Image loaded ✅'),
],
),
const SizedBox(height: 12),
SegmentedButton<bool>(
segments: const [
ButtonSegment(value: false, label: Text('Grid W x H')),
ButtonSegment(value: true, label: Text('Cap size (px)')),
],
selected: {_useCapSize},
onSelectionChanged: (s) {
setState(() => _useCapSize = s.first);
_scheduleRegenerate();
},
),
const SizedBox(height: 8),
if (!_useCapSize)
Row(
children: [
Expanded(
child: TextField(
controller: _gridWidthCtrl,
keyboardType: TextInputType.number,
decoration:
const InputDecoration(labelText: 'Grid Width'),
),
),
const SizedBox(width: 8),
Expanded(
child: TextField(
controller: _gridHeightCtrl,
keyboardType: TextInputType.number,
decoration:
const InputDecoration(labelText: 'Grid Height'),
),
),
],
)
else
TextField(
controller: _capSizeCtrl,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: 'Approx cap size in source image (pixels)',
),
),
const SizedBox(height: 16),
Row(
children: [
const Expanded(
child: Text(
'Cap Palette',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
),
IconButton(
onPressed: _addCapDialog,
icon: const Icon(Icons.add_circle_outline),
),
],
),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
for (int i = 0; i < _palette.length; i++)
Chip(
avatar: CircleAvatar(backgroundColor: _palette[i].color),
label: Text(_palette[i].name),
onDeleted: _palette.length <= 1
? null
: () {
setState(() => _palette.removeAt(i));
_scheduleRegenerate();
},
),
],
),
const SizedBox(height: 16),
if (_result != null) ...[
Text(
'Preview (${_result!.width} x ${_result!.height})',
style:
const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
RepaintBoundary(
child: AspectRatio(
aspectRatio: _result!.width / _result!.height,
child: Image.memory(
_result!.previewPng,
fit: BoxFit.fill,
filterQuality: FilterQuality.none,
gaplessPlayback: true,
),
),
),
const SizedBox(height: 16),
const Text(
'Bill of Materials',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
..._result!.sortedCounts.map(
(e) => ListTile(
dense: true,
leading: CircleAvatar(backgroundColor: e.key.color),
title: Text(e.key.name),
trailing: Text('${e.value} caps'),
),
),
],
],
),
),
);
}
Color? _parseHex(String raw) {
final hex = raw.trim().replaceFirst('#', '');
if (hex.length != 6) return null;
final value = int.tryParse(hex, radix: 16);
if (value == null) return null;
return Color(0xFF000000 | value);
}
}
class CapColor {
final String name;
final Color color;
const CapColor({required this.name, required this.color});
}
class MosaicResult {
final int width;
final int height;
final List<int> assignments;
final List<CapColor> palette;
final Map<CapColor, int> counts;
final List<MapEntry<CapColor, int>> sortedCounts;
final Uint8List previewPng;
MosaicResult({
required this.width,
required this.height,
required this.assignments,
required this.palette,
required this.counts,
required this.sortedCounts,
required this.previewPng,
});
}
Map<String, dynamic> _generateMosaicIsolate(Map<String, dynamic> request) {
final source = request['source'] as Uint8List;
final useCapSize = request['useCapSize'] as bool;
final defaultGridW = request['gridW'] as int;
final defaultGridH = request['gridH'] as int;
final capSize = request['capSize'] as int;
final paletteRaw = (request['palette'] as List).cast<Map>();
final decoded = img.decodeImage(source);
if (decoded == null) {
return <String, dynamic>{
'width': 1,
'height': 1,
'assignments': <int>[0],
'counts': <int>[1],
'palette': paletteRaw,
'previewPng': Uint8List.fromList(
img.encodePng(img.Image(width: 1, height: 1)),
),
};
}
final gridW = useCapSize
? math.max(1, (decoded.width / capSize).round())
: defaultGridW;
final gridH = useCapSize
? math.max(1, (decoded.height / capSize).round())
: defaultGridH;
final scaled = img.copyResize(
decoded,
width: gridW,
height: gridH,
interpolation: img.Interpolation.average,
);
final paletteValues = paletteRaw.map((e) => e['value'] as int).toList();
final paletteLab = paletteValues.map(_argbToLab).toList(growable: false);
final assignments = List<int>.filled(gridW * gridH, 0);
final counts = List<int>.filled(paletteValues.length, 0);
final nearestCache = <int, int>{};
final labCache = <int, List<double>>{};
for (int y = 0; y < gridH; y++) {
for (int x = 0; x < gridW; x++) {
final pix = scaled.getPixel(x, y);
final rgb = (pix.r.toInt() << 16) | (pix.g.toInt() << 8) | pix.b.toInt();
final cached = nearestCache[rgb];
if (cached != null) {
assignments[y * gridW + x] = cached;
counts[cached]++;
continue;
}
final srcLab = labCache.putIfAbsent(rgb, () => _rgbToLab(rgb));
int bestIdx = 0;
double bestDistance = double.infinity;
for (int i = 0; i < paletteLab.length; i++) {
final d = _deltaE76(srcLab, paletteLab[i]);
if (d < bestDistance) {
bestDistance = d;
bestIdx = i;
}
}
nearestCache[rgb] = bestIdx;
assignments[y * gridW + x] = bestIdx;
counts[bestIdx]++;
}
}
final preview = img.Image(width: gridW, height: gridH);
for (int y = 0; y < gridH; y++) {
for (int x = 0; x < gridW; x++) {
final idx = assignments[y * gridW + x];
final argb = paletteValues[idx];
preview.setPixelRgba(
x,
y,
(argb >> 16) & 0xFF,
(argb >> 8) & 0xFF,
argb & 0xFF,
255,
);
}
}
return <String, dynamic>{
'width': gridW,
'height': gridH,
'assignments': assignments,
'counts': counts,
'palette': paletteRaw,
'previewPng': Uint8List.fromList(img.encodePng(preview, level: 1)),
};
}
List<double> _argbToLab(int argb) {
final rgb = argb & 0x00FFFFFF;
return _rgbToLab(rgb);
}
List<double> _rgbToLab(int rgb) {
double r = ((rgb >> 16) & 0xFF) / 255.0;
double g = ((rgb >> 8) & 0xFF) / 255.0;
double b = (rgb & 0xFF) / 255.0;
r = r <= 0.04045 ? r / 12.92 : math.pow((r + 0.055) / 1.055, 2.4).toDouble();
g = g <= 0.04045 ? g / 12.92 : math.pow((g + 0.055) / 1.055, 2.4).toDouble();
b = b <= 0.04045 ? b / 12.92 : math.pow((b + 0.055) / 1.055, 2.4).toDouble();
final x = (r * 0.4124 + g * 0.3576 + b * 0.1805) / 0.95047;
final y = (r * 0.2126 + g * 0.7152 + b * 0.0722) / 1.00000;
final z = (r * 0.0193 + g * 0.1192 + b * 0.9505) / 1.08883;
double f(double t) => t > 0.008856
? math.pow(t, 1.0 / 3.0).toDouble()
: (7.787 * t) + (16 / 116);
final fx = f(x);
final fy = f(y);
final fz = f(z);
final l = (116 * fy) - 16;
final a = 500 * (fx - fy);
final bStar = 200 * (fy - fz);
return [l, a, bStar];
}
double _deltaE76(List<double> lab1, List<double> lab2) {
final dl = lab1[0] - lab2[0];
final da = lab1[1] - lab2[1];
final db = lab1[2] - lab2[2];
return math.sqrt(dl * dl + da * da + db * db);
}