【问题标题】:How do I get the RGB values from an image in Flutter?如何从 Flutter 中的图像中获取 RGB 值?
【发布时间】:2021-09-13 00:58:14
【问题描述】:

我正在为我的对象检测服务器创建一个移动客户端。我已经有一个运行良好的 python 客户端,它将图像作为输入,通过 HTTP 请求将其发送到服务器,并以 json 响应的形式接收预测。我正在尝试在我相当陌生的 Dart 中实现相同的目标。

我的python代码将输入的JPG图像转换为RGB值的numpy数组,格式如下(以5x4图像为例)-

[
[[182, 171, 153], [203, 188, 169], [242, 214, 200], [255, 235, 219], [155, 111, 98]],
[[181, 171, 146], [204, 190, 164], [255, 237, 214], [177, 142, 120], [84, 42, 20]], 
[[176, 168, 129], [218, 206, 166], [180, 156, 118], [91, 59, 21], [103, 64, 25]],
[[186, 180, 132], [166, 156, 107], [91, 68, 24], [94, 63, 17], [122, 84, 39]]
]

在我的 dart 代码中,我尝试使用 - 将图像转换为 8 位无符号整数列表 -

Uint8List inputImg = (await rootBundle.load("assets/test.jpg")).buffer.asUint8List()

对于同一张 5x4 图像,它为我提供了超过 800 个整数的长数组。

在使用两张单像素图像(一张黑色和一张白色)对其进行测试时,Uint8List 的大部分似乎都在重复。我隔离了数组的不同部分,它们与颜色的预期 RGB 值不对应(我预期 [0 0 0] 和 [255 255 255],但得到了类似 255、0、63、250、0、 255, 0 和 254, 254, 40, 3 分别表示两者)

我只需要图像中的 RGB 值。非常感谢有人指出我正确的方向!

【问题讨论】:

标签: flutter dart


【解决方案1】:

图像在存储时通常为compressed。根据文件扩展名,我猜您使用的是 JPEG 编码。这意味着存储在assets/test.jpg 文件中的数据不是颜色数组。如果一切都以这种方式完成,那将是对数据存储的低效使用。要获得该颜色数组,您需要解码图像。这可以通过image 包来完成。

为此,首先将包添加为依赖项,将以下内容添加到pubspec.yaml:

dependencies:
  image: ^3.0.4

您应该遵循相同的方法来获取编码的图像数据。但是你需要解码它。

final Uint8List inputImg = (await rootBundle.load("assets/test.jpg")).buffer.asUint8List();
final decoder = JpegDecoder();
final decodedImg = decoder.decodeImage(inputImg);
final decodedBytes = decodedImg.getBytes(format: Format.rgb);

decodedBytes 包含 RGB 格式的所有像素值的单个深度列表。要将其转换为您想要的格式,只需遍历这些值并将它们添加到新列表中即可。

List<List<List<int>> imgArr = [];
for(int y = 0; y < decodedImage.height; y++) {
  imgArr.add([]);
  for(int x = 0; x < decodedImage.width; x++) {
    int red = decodedBytes[y*decodedImage.width*3 + x*3];
    int green = decodedBytes[y*decodedImage.width*3 + x*3 + 1];
    int blue = decodedBytes[y*decodedImage.width*3 + x*3 + 2];
    imgArr[y].add([red, green, blue]);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-10
    • 2020-06-20
    • 2012-08-11
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    相关资源
    最近更新 更多