You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Dart中将PyTorch Mobile输出的一维二值像素列表转为图像?

将二进制掩码转换为Flutter可展示/保存的图像

你已经完成了掩码的二值化处理(得到0/255的一维Uint8List),接下来可以通过image包快速将其转换为可展示或保存的图像,具体步骤如下:

1. 添加依赖

在pubspec.yaml中添加图像处理和路径相关的依赖:

dependencies:
  flutter:
    sdk: flutter
  image: ^4.0.17 # 用于处理图像数据
  path_provider: ^2.1.1 # 可选,方便获取本地存储路径

2. 转换一维数据为图像对象

导入所需包后,将你的result_list_Uint8转换为image包的Image对象(对应512×512的灰度图):

import 'package:image/image.dart' as img;
import 'dart:typed_data';

// 转换一维Uint8List为灰度图像
img.Image maskImage = img.Image.fromBytes(
  width: 512,
  height: 512,
  bytes: result_list_Uint8.buffer,
  format: img.Format.l8, // 8位灰度格式,匹配0-255的像素值
);

3. 在Flutter UI中展示

将图像对象编码为PNG字节后,用Image.memory组件展示:

import 'package:flutter/widgets.dart';

// 编码为PNG格式
Uint8List maskPngBytes = img.encodePng(maskImage);

// 直接展示掩码
Image.memory(maskPngBytes);

// 若要和原图叠加展示(半透明效果)
Stack(
  children: [
    Image.file(File(filePath)), // 原始图像
    Image.memory(
      maskPngBytes,
      color: Colors.blue.withOpacity(0.4), // 自定义掩码颜色和透明度
      colorBlendMode: BlendMode.srcOver,
    ),
  ],
)

4. 保存到本地存储

将图像编码为PNG/JPEG后写入本地文件:

import 'dart:io';
import 'package:path_provider/path_provider.dart';

Future<void> saveMaskToStorage(img.Image maskImage) async {
  // 获取应用文档目录(避免权限问题)
  Directory appDocDir = await getApplicationDocumentsDirectory();
  String savePath = '${appDocDir.path}/segmentation_mask.png';

  // 编码为PNG字节
  Uint8List pngBytes = img.encodePng(maskImage);

  // 写入文件
  await File(savePath).writeAsBytes(pngBytes);
  print('掩码已保存至: $savePath');
}

// 调用保存方法
saveMaskToStorage(maskImage);

优化你的二值化代码

原来的forEach可以用map简化,更简洁高效:

List<int> result_list = prediction.map((element) => element > 0 ? 255 : 0).toList();
Uint8List result_list_Uint8 = Uint8List.fromList(result_list);

内容的提问来源于stack exchange,提问作者kotschi123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 17:18:18