'Image filter gets stronger every loop - p5.js
I have made my own image filters. When the mouse is clicked on the original (left) image, it is meant to create a radial blur effect on the processed (right) image. However, after testing it I have found that it only works if I have my mouse over the picture as it's loading. Then, if I click my mouse, the original picture is processed and it looks like the filter gets stronger on the already processed image to the right like it gets another filter applied on top. This continues the more I click. Would anyone have an idea of what I've done wrong? I'm not sure where the issue with my code is.
var img;
function preload() {
img = loadImage("https://media.makeameme.org/created/doesnt-know-why-gxsyb3.jpg");
}
function setup() {
createCanvas((img.width * 2), img.height);
}
function draw() {
background(125);
image(img, 0, 0);
image(FinalFilter(img), img.width, 0);
noLoop();
}
function mousePressed() {
loop();
}
function FinalFilter(input) {
var resultImg = createImage(input.width, input.height);
resultImg = sepia(input);
resultImg = radialBlurFilter(resultImg);
resultImg.updatePixels();
return resultImg;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
Solution 1:[1]
As Sam mentioned in the comment, you're re-applying the filters to the same pixels each time: hence the cumulative effect.
You could simply make a copy of the input p5.Image using get() and apply the filters to that instead of the original image (which after the first filter is altered):
var matrix = [[1,1,1],
[1,3,1],
[1,1,1]];
var img;
function preload() {
img = loadImage("https://media.makeameme.org/created/doesnt-know-why-gxsyb3.jpg");
}
function setup() {
createCanvas((img.width * 2), img.height);
}
function draw() {
background(125);
image(img, 0, 0);
image(FinalFilter(img), img.width, 0);
noLoop();
}
function mousePressed() {
loop();
}
function FinalFilter(input) {
var resultImg = createImage(input.width, input.height);
resultImg = sepia(input);
resultImg = radialBlurFilter(resultImg);
resultImg.updatePixels();
return resultImg;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.min.js"></script>
The confusion might come from the FinalFilter function?
One option, as mentioned above, you could simply clone the input image with get() first:
function FinalFilter(input) {
var resultImg = createImage(input.width, input.height);
resultImg = sepiaFilter(input.get());
resultImg = radialBlurFilter(resultImg);
// this call to `updatePixels()` is a bit redundant since sepiaFilter and radialBlurFilter both call `updatePixels()` on the reference image passed as an argument
resultImg.updatePixels();
return resultImg;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Emilia Hardej |
