renderBoxesOnImage method
- File image,
- List<
ResultObjectDetection?> recognitions, { - Color? boxesColor,
- bool showPercentage = true,
Renders object detection results as an overlay on the original image.
Creates a Flutter widget that displays the original image with bounding boxes and labels overlaid on detected objects.
@param image The original image file @param recognitions List of detection results to display @param boxesColor Optional color for bounding boxes @param showPercentage Whether to show confidence percentages @return A widget displaying the image with detection overlays
Implementation
Widget renderBoxesOnImage(
File image, List<ResultObjectDetection?> recognitions,
{Color? boxesColor, bool showPercentage = true}) {
print(recognitions.length);
return LayoutBuilder(builder: (context, constraints) {
debugPrint(
'Max height: ${constraints.maxHeight}, max width: ${constraints.maxWidth}');
double factorX = constraints.maxWidth;
double factorY = constraints.maxHeight;
return Stack(
children: [
Positioned(
left: 0,
top: 0,
width: factorX,
height: factorY,
child: Container(
child: Image.file(
image,
fit: BoxFit.fill,
)),
),
...recognitions.map((re) {
if (re == null) {
return Container();
}
Color usedColor;
if (boxesColor == null) {
//change colors for each label
usedColor = Colors.primaries[
((re.className ?? re.classIndex.toString()).length +
(re.className ?? re.classIndex.toString())
.codeUnitAt(0) +
re.classIndex) %
Colors.primaries.length];
} else {
usedColor = boxesColor;
}
print({
"left": re.rect.left.toDouble() * factorX,
"top": re.rect.top.toDouble() * factorY,
"width": re.rect.width.toDouble() * factorX,
"height": re.rect.height.toDouble() * factorY,
});
return Positioned(
left: re.rect.left * factorX,
top: re.rect.top * factorY - 20,
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
height: 20,
alignment: Alignment.centerRight,
color: usedColor,
child: Text(
"${re.className ?? re.classIndex.toString()}_${showPercentage
? "${(re.score * 100).toStringAsFixed(2)}%"
: ""}",
),
),
Container(
width: re.rect.width.toDouble() * factorX,
height: re.rect.height.toDouble() * factorY,
decoration: BoxDecoration(
border: Border.all(color: usedColor, width: 3),
borderRadius: const BorderRadius.all(Radius.circular(2))),
child: Container(),
),
],
),
);
})
],
);
});
}