xxxxxxxxxx
117
/*
* I started translating
* https://github.com/kimasendorf/ASDFPixelSort/blob/master/ASDFPixelSort.pde
* to p5.js but I didn't finish :(
*/
let img;
let colorPixels = [];
function preload() {
img = loadImage('sufjan.jpg');
}
function setup() {
print(img.width);
print(img.height);
img.resize(img.width/2, img.height/2);
createCanvas(img.width, img.height);
noLoop();
}
function colorToInt(c) {
return parseInt(c.toString('#rrggbb').substr(1), 16);
}
function copyPixelsToColors() {
for (let i = 0; i < img.pixels.length; i += 4) {
let r = img.pixels[i];
let g = img.pixels[i+1];
let b = img.pixels[i+2];
let a = img.pixels[i+3];
colorPixels.push(color(r,g,b,a));
}
}
function copyColorsToPixels() {
for (let i = 0; i < colorPixels.length; i+=1) {
img.pixels[4*i] = red(colorPixels[i]);
img.pixels[4*i+1] = green(colorPixels[i]);
img.pixels[4*i+2] = blue(colorPixels[i]);
img.pixels[4*i+3] = alpha(colorPixels[i]);
}
}
function sortColorAsInt(a,b) {
let ac = colorToInt(a);
let bc = colorToInt(b);
if (a < b) return -1;
if (a > b) return 1;
if (a === b) return 0;
}
function draw() {
background(220);
img.loadPixels();
copyPixelsToColors();
for (let y = 0; y < img.height; y +=1) {
sortRow(y);
}
copyColorsToPixels();
img.updatePixels();
image(img, 0, 0);
}
function sortRow(y) {
// print('row: ' + y);
// black threshold
// play around with this number!!
let blackThreshold = 5999999;
let brightnessThreshold = 60;
let sortStart = -1;
let sortEnd = -1;
while (sortEnd < img.width-1) {
sortStart = -1;
let x = sortEnd + 1;
for (; x < img.width; x +=1) {
let c = colorPixels[x + y*width];
// let brightnessValue = brightness(c);
let colorAsInt = colorToInt(c);
//print(colorAsInt);
// let b = brightness(c);
if (sortStart < 0) {
// if (brightnessValue < brightnessThreshold) {
if (colorAsInt > blackThreshold) {
// print('sortStart: ' + colorAsInt);
sortStart = x;
}
}
if (sortStart > -1) {
if (colorAsInt < blackThreshold || x === img.width - 1) {
// print('sortEnd: ' + colorAsInt);
sortEnd = x;
break;
}
}
}
print(sortStart);
print(sortEnd);
if (sortStart < 0) break;
let sortArray = colorPixels.slice(sortStart + y*width, sortEnd + y*width);
// print('sorting row: ' + y);
sortArray.sort(sortColorAsInt);
for (let i = 0; i < sortArray.length; i += 1) {
colorPixels[sortStart + y*width + i] = sortArray[i];
}
}
// sort entire row
// let sortStart = y*img.width;
// let sortEnd = (y+1)*img.width - 1;
// let sortArray = colorPixels.slice(sortStart, sortEnd);
// sortArray.sort(sortColorAsInt);
// for (let i = 0; i < sortArray.length; i += 1) {
// colorPixels[sortStart + i] = sortArray[i];
// }
}