Using pixels
as the name for its parameter, your pixelShuffle
function seems to confuse the distinction between the image and the p5.js pixels
array.
Note, from p5.js: Reference: pixels, that pixels
is a Uint8ClampedArray
. For a description of the methods associated with that type, see MDN Web Docs: Uint8ClampedArray.
Try this example as an initial pattern for your script:
let capture;
let selected;
function setup() {
createCanvas(400, 300);
background(150);
// noLoop();
capture = createCapture(VIDEO);
capture.hide();
selected = createImage(50, 50);
}
function draw() {
image(capture, 0, 0);
selected = capture.get(100, 100, 150, 150)
selected = pixelShuffle(selected);
image(selected, 50, 50);
}
function pixelShuffle(img) {
img.loadPixels();
// shuffle img.pixels, which is a Uint8ClampedArray
shuffle(img.pixels, true);
img.updatePixels();
return img;
}
All the pixelShuffle
function does in the above example is simply use the p5.js shuffle
function to shuffle img.pixels
randomly, which creates noise. However, the important thing is that it demonstrates that the function, as written, does return a changed image.
Beginning with that example, you can replace these lines in the pixelShuffle
function with your own code for shuffling img.pixels
:
// shuffle img.pixels, which is a Uint8ClampedArray
shuffle(img.pixels, true);
Be careful to only use methods on img.pixels
that can be applied to the Uint8ClampedArray
type.
EDITED on July 11, 2021 to add the following:
Since img.pixels
is a Uint8ClampedArray
, you will not be able to use the splice
method on it, so you will need to find an alternative.
Below is an example of a pixelShuffle
method that swaps portions of img.pixels
, followed by a resulting image. You can adapt it to your needs by modifying the code.
function pixelShuffle(img) {
img.loadPixels();
// modify img.pixels, which is a Uint8ClampedArray
let temp;
for (i = 0; i < img.pixels.length / 2; i += 4) {
// compare the red components of the pixels
if (img.pixels[i] > img.pixels[i + img.pixels.length / 2]) {
// swap the red components
temp = img.pixels[i];
img.pixels[i] = img.pixels[i + img.pixels.length / 2];
img.pixels[i + img.pixels.length / 2] = temp;
}
}
img.updatePixels();
return img;
}