Different filters to one image

#1

Hi, I’m preloading an image and I’m loading it every 10 seconds in a different position of the canvas. I want to apply to my image a new different filter every time I load it (to the image only, not to all the canvas). The problem is that the filters are overlaying every time. I would like to clean all the filters before applying a new one. The functions pop() and resetMatrix() aren’t working in this case.
Is it possible to do this without using objects?

if (cont == 10) {
   translate(random(0, windowWidth), random(0, windowHeight)); 
   filtre = random(filtres);
   img.filter(filtre); 
   image(img, 0, 0, x, y); 
   resetMatrix();
 } 

Thanks!

1 Like
#2

As far as I know filters in p5.js only go one way. There’s no way to reverse the effects if you apply a filter.

That said I would just store a the 2 copies of the image. One which has no filters and one to apply filters to. Whenever you want to apply new filters you can copy the original into the filtered one.

It does take up a twice as much memory but unless you’re loading a ton of images it shouldn’t make much of a difference.

Here’s a basic example to demonstrate the idea.

let originalImg; // this will hold the original image
let filteredImg; // this will  a copy that has filters applied

function preload() {
  originalImg = loadImage('https://i.kinja-img.com/gawker-media/image/upload/s--PnSCSSFQ--/c_scale,f_auto,fl_progressive,pg_1,q_80,w_800/z7jcryloxjedsztssw39.jpg'); // A random image I found on the internet
}

function setup() {
  createCanvas(400, 400);
  filteredImg = createImage(originalImg.width, originalImg.height);
}

function draw() {
  background(220);

  filteredImg.copy(originalImg, 0, 0, originalImg.width, originalImg.height, 0, 0, filteredImg.width, filteredImg.height);
  // copy each time you want to go back to the original
  
  let filterToApply;
  if (random() > 0.5) {
    filterToApply = ERODE;
  } else {
    filterToApply = BLUR;
  }
  
  filteredImg.filter(filterToApply); // then apply a random filter
  image(filteredImg, 0, 0);
}

The copy command is a little over complicated here’s a link to the documentation if it seems confusing.

Also in future it’s much easier to read code if you use the </> button when posting.

1 Like