2

I'm trying to deleting light background from an image using the image package. Here's what I've cooked up so far.

import 'package:image/image.dart';

class SignatureExtractor {
  final Image image;

  SignatureExtractor({required this.image});

  Future<Image> extract() async {
    for (var i = 0; i < image.width; i++) {
      for (var j = 0; j < image.height; j++) {
        var color = image.getPixel(i, j);
        var red = (color >> 16) & 0xff;
        var green = (color >> 8) & 0xff;
        var blue = color & 0xff;
        var alpha = 0xff;
        if ((red + green + blue) > 30) {
          alpha = 0x00;
        }
        image.setPixelRgba(i, j, red, green, blue, alpha);
      }
    }
    return image;
  }
}

Will this be sufficient for the purpose? Is there anything I can do to make it more efficient?

2

1 Answer 1

3
+25

You can try setting the alpha = 0.0 if brightness is more than some value = x. For example, here I am using lightness = 0.8 (range of 0.0 to 1.0).

import 'package:flutter/material.dart';
import 'package:image/image.dart' as i;


class SignatureExtractor {
  final i.Image image;

  SignatureExtractor({required this.image});

  Future<i.Image> extract() async {
    for (var i = 0; i < image.width; i++) {
      for (var j = 0; j < image.height; j++) {
        final hsl = HSLColor.fromColor(Color(image.getPixel(i, j)));
        if (hsl.lightness > 0.8) {
          image.setPixel(i, j, hsl.withAlpha(0.0).toColor().value);
        }
      }
    }
    return image;
  }
}
3
  • Hi, thank you for the answer. Sorry for the late reply. Great idea using HSLColor and lightness. Did you think about maybe keeping nearby pixels with half transparency maybe so that the image looks smooth? I tried but couldn't achieve any satisfactory results.
    – Binoy Babu
    Jan 12 at 6:39
  • You could do something like gradually increasing the alpha values of neighbouring pixels so that the image could look smooth. You'll have to trial and error to find what pixel distance should be used.
    – Rahul
    Jan 12 at 8:33
  • If you could provide sample image, I can try it out to come up with some solution.
    – Rahul
    Jan 12 at 8:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.