meltingice / CamanJS

Javascript HTML5 (Ca)nvas (Man)ipulation
http://camanjs.com
BSD 3-Clause "New" or "Revised" License
3.55k stars 404 forks source link

pixel subset manipulation #132

Open deanmalmgren opened 10 years ago

deanmalmgren commented 10 years ago

I have an application where I'd like to manipulate a subset of the pixels in an image. For example, imagine looking at a selfie and making all pixels that aren't associated with a face transparent. I have another method that identifies the equivalent of non-face pixels so all I need to do is manipulate specific x,y coordinates with Caman. After poking around for a while and trying different things, it appears that the only way to edit pixels is in a custom filter, but this isn't terribly fast because every non-face pixel is manipulated N*M times for an NxM image:

// non_face_pixels = [{x:13, y:27}, ...]
Caman.Filter.register("selfie", function (non_face_pixels) {
  // in principal, we could just modify the non_face_pixels here, but since this method 
  // is run for every single pixel, every non_face_pixel is edited NxM times for an 
  // NxM pixel image
  this.process("selfie", function (rgba) {
    var self = this;
    non_face_pixels.forEach(function (p, i) {
      self.putPixel(p.x, p.y, {r:0, g:0, b:0, a:0});
    });
    return rgba;
  });
});

Is there, in fact, a way to edit a subset of pixels without creating a filter to do it? If not, it would be really nice to expose a method to edit pixels at the Caman level rather than requiring this to happen inside of a filter. Any chance this is in the development pipeline or easy to incorporate?

I'm a CoffeeScript n00b but I'm happy to try and take a crack at an implementation if you can point me in the right direction.