【问题标题】:Flutter / Dart : convert image to 1 bit black and whiteFlutter / Dart:将图像转换为 1 位黑白
【发布时间】:2019-09-03 14:37:40
【问题描述】:

我正在编写代码以使用 ESC * 命令(使用 ESC POS 热敏收据打印机)打印图像。

基本上,我正在尝试将 Python 算法用于 Dart/Flutter。听起来很简单:打开图像 -> 灰度 -> 反转颜色 -> 转换为黑白 1 位:

im = Image.open(filename)
im = im.convert("L")  # Invert: Only works on 'L' images
im = ImageOps.invert(im)  # Bits are sent with 0 = white, 1 = black in ESC/POS

print(len(im.tobytes())) # len = 576 (image size: 24*24)
im = im.convert("1")  # Pure black and white
print(len(im.tobytes())) # leng = 72 (image size: 24*24)
...

我只有最后一步(1位转换)有问题。

如您所见,Python 代码(Pillow 库)将减少 im.convert("1") 命令后的字节数,而这正是我正确生成 ESC/POS 命令所需要的。每个值都在 0 到 255 之间。

如何使用 Dart 实现?

这是我的代码:

import 'package:image/image.dart';

const String filename = './test_24x24.png';
final Image image = decodeImage(File(filename).readAsBytesSync());

grayscale(image);
invert(image);

源图片:24px * 24px

最后,我在 RGB 模式下有一个包含 (24 * 24 * 3) 字节的灰色/反转图像。由于灰度,所有的 r/g/b 值都是相等的,所以我只能保留一个通道,它给我 (24 * 24) 字节。

如何实现最后一步im.convert("1"),只保留24 * 3字节?

【问题讨论】:

    标签: python image flutter dart thermal-printer


    【解决方案1】:

    遍历 576 个灰度字节,将每个字节与阈值进行比较,并将这些位打包成字节(或者更方便的是整数)。

    这是一个使用来自 package:raw 的辅助函数的示例,但您可以将其内联,因为它相对简单。

      Uint8List img24x24 = Uint8List(24 * 24); // input 24x24 greyscale bytes [0-255]
      Uint32List img24 = Uint32List(24); // output 24 packed int with 24 b/w bits each
      final threshold = 127; // set the greyscale -> b/w threshold here
      for (var i = 0; i < 24; i++) {
        for (var j = 0; j < 24; j++) {
          img24[i] = transformUint32Bool(
            img24[i],
            24 - j,
            img24x24[i * 24 + j] > threshold, // or < threshold to do the invert in one step
          );
        }
      }
    

    【讨论】:

    • 非常感谢,真的很有帮助!
    猜你喜欢
    • 2022-09-28
    • 2013-03-17
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 2013-04-21
    • 2021-02-27
    • 2021-02-26
    相关资源
    最近更新 更多