xxxxxxxxxx
102
//https://happycoding.io/examples/p5js/images/pixel-sorter
//https://editor.p5js.org/codingtrain/sketches/zxruKuft9
let img, sorted;
function preload() {
img = loadImage("beach.jpg");//point.jpg");
}
function sortPixels() {
sorted.loadPixels();
// Selection sort
for (let index = 0; index < sorted.pixels.length-1; index += 4) {
for (let n = 0; n < 1; n++) {
let record = -1;
let selectedPixel = index;
for (let j = index; j < sorted.pixels.length; j += 4) {
let pix = color(sorted.pixels[j], sorted.pixels[j + 1], sorted.pixels[j + 2], sorted.pixels[j + 3]);
let b = hue(pix);
if (b > record) {
selectedPixel = j;
record = b;
}
}
// Swap selectedPixel with i
let temp = [];
temp[0] = sorted.pixels[index];
temp[1] = sorted.pixels[index + 1];
temp[2] = sorted.pixels[index + 2];
temp[3] = sorted.pixels[index + 3];
sorted.pixels[index] = sorted.pixels[selectedPixel];
sorted.pixels[index + 1] = sorted.pixels[selectedPixel + 1];
sorted.pixels[index + 2] = sorted.pixels[selectedPixel + 2];
sorted.pixels[index + 3] = sorted.pixels[selectedPixel + 3];
sorted.pixels[selectedPixel] = temp[0];
sorted.pixels[selectedPixel + 1] = temp[1];
sorted.pixels[selectedPixel + 2] = temp[2];
sorted.pixels[selectedPixel + 3] = temp[3];
if (index < sorted.pixels.length - 1) {
index += 4;
}
}
}
sorted.updatePixels();
}
function setup() {
createCanvas(img.width, img.height);
noSmooth();
sorted = img.get();
/*
for (let index = 0; index < sorted_img.pixels.length-1; index += 4) {
for (let n = 0; n < 1; n++) {
let record = -1;
let selectedPixel = index;
for (let j = index; j < sorted_img.pixels.length; j += 4) {
let pix = color(sorted_img.pixels[j],
sorted_img.pixels[j+1],
sorted_img.pixels[j+2],
sorted_img.pixels[j+3]);
let b = hue(pix);
if (b > record) {
selectedPixel = j;
record = b;
}
}
// swap
let temp = [];
temp[0] = sorted_img.pixels[index];
temp[1] = sorted_img.pixels[index+1];
temp[2] = sorted_img.pixels[index+2];
temp[3] = sorted_img.pixels[index+3];
sorted_img.pixels[index] = sorted_img.pixels[selectedPixel];
sorted_img.pixels[index+1] = sorted_img.pixels[selectedPixel+1];
sorted_img.pixels[index+2] = sorted_img.pixels[selectedPixel+2];
sorted_img.pixels[index+3] = sorted_img.pixels[selectedPixel+3];
sorted_img.pixels[selectedPixel] = temp[0];
sorted_img.pixels[selectedPixel+1] = temp[1];
sorted_img.pixels[selectedPixel+2] = temp[2];
sorted_img.pixels[selectedPixel+3] = temp[3];
}
}*/
// sorted_img.loadPixels();
sortPixels();
// sorted_img.updatePixels();
image(sorted, 0, 0);
}
function draw() {
noLoop();
// background(220);
}