How to slow down random color generator in Processing? - animation

Hi everyone – I want to make a grid pattern of rectangles with random filling colors out of an array.I can get it done the way I want – but the random selection is way too speedy.
I tried to slow everything down with frameRate(); – but this slows down the whole animation. (For example if I want to add something else). Then I tried to slow it down with if(frameCount%20 == 0) {…} but this does not keep the drawn grid – only lets it appear every XXX frames for one frame – does someone have an idea how I could slow down the lets call it "Color Noise"? – Thank you for any kind of help!
float size = 20;
color cbw = color(0, 0, 0); //defines BLACK
color cg = color(0, 255, 0); //defines GREEN
color cb = color(0, 0, 255); //defines BLUE
color cw = color(255, 255, 255); //defines WHITE
color[] colors = { //random selects one of above colors
cbw, cg, cb, cw
};
void setup() {
size(1080, 1080);
}
void draw() {
background(255);
for (int x = 0; x < width/size; x++) {
for (int y = 0; y < height/size; y++) {
color c1 = (colors[int(random(0, 4))]); //assigns a random color from above to c1-4
fill(c1);
noStroke();
rect(size*x, size*y, size, size);
}
}
}

You're on the right track with frameCount % 20. (Alternatively you can use millis())
The main issue is the colour selection is tightly coupled with the rectangle drawing.
In plain English, currently you can only select random colours and render at the same time, but not select colours and render independently (e.g. at different times)
One option is to use an array to store the colours for every rectangle which you can use twice:
to write values to: pick random colours
to read values from: when rendering the rectangles
Here's a modified version of your sketch that illustrated the idea above:
float size = 20;
color cbw = color(0, 0, 0); //defines BLACK
color cg = color(0, 255, 0); //defines GREEN
color cb = color(0, 0, 255); //defines BLUE
color cw = color(255, 255, 255); //defines WHITE
color[] colors = { //random selects one of above colors
cbw, cg, cb, cw
};
// all colors for each rect
color[][] rectColors;
void setup() {
size(1080, 1080);
// allocate invidual rect colours
rectColors = new color[width/(int)size][height/(int)size];
}
void draw() {
background(255);
if(frameCount%20 == 0){
// randomize colours
int numColors = colors.length;
for (int x = 0; x < width/size; x++) {
for (int y = 0; y < height/size; y++) {
rectColors[x][y] = colors[int(random(0, numColors))];
}
}
}
for (int x = 0; x < width/size; x++) {
for (int y = 0; y < height/size; y++) {
color c1 = rectColors[x][y]; //assigns a random color from above to c1-4
fill(c1);
noStroke();
rect(size*x, size*y, size, size);
}
}
}
Personally, I would do a few extra things to make this easier to read and potentially re-use in other sketches:
change float size = 20; to int size = 20; assuming you want the grid cells to land on whole pixels. This removes the need to cast (e.g. width/(int)size)
cache/store data that is often re-used (such as grid rows and columns)
encapsulate the loops that randomize colours and render rectangles into separate functions. Even something as simple as functions that return no values and take no arguments (e.g. much like void setup() for example)
Here is what that could look like:
int size = 20;
color cbw = color(0, 0, 0); //defines BLACK
color cg = color(0, 255, 0); //defines GREEN
color cb = color(0, 0, 255); //defines BLUE
color cw = color(255, 255, 255); //defines WHITE
color[] colors = { //random selects one of above colors
cbw, cg, cb, cw
};
// all colours for each rect
color[][] rectColors;
// grid dimensions
int cols;
int rows;
void setup() {
size(1080, 1080);
// compute grid dimensions
cols = width / size;
rows = height / size;
// allocate invidual rect colours
rectColors = new color[cols][rows];
// call randomize colours function
randomizeColors();
}
// declare randomize colours function
void randomizeColors(){
// read array length, avoding the previosuly hardcoded value (4)
int numColors = colors.length;
for (int x = 0; x < cols; x++) {
for (int y = 0; y < rows; y++) {
rectColors[x][y] = colors[int(random(0, numColors))];
}
}
}
void drawRectangles(){
for (int x = 0; x < cols; x++) {
for (int y = 0; y < rows; y++) {
color c1 = rectColors[x][y]; //read a random color
fill(c1);
noStroke();
rect(size * x, size * y, size, size);
}
}
}
void draw() {
background(255);
if(frameCount % 20 == 0){
randomizeColors();
}
drawRectangles();
}

Related

Colored Letters with Colorcycle | Processing

I found a program, that generates random letters in a grid and gives them a random color.
How can I have the letters cange in color or brightness while the program is running?
(sourcecode: https://happycoding.io/examples/processing/for-loops/letters)
I tried making the fill(r, g, b) have a 'r' that cycles from 1 to 255 and back while having 'g' and 'b' at 0, but I could´t get it to update the color. Im cinda new to programming so I´d love to know how I could make that happen.
First, let's change the fill method to accept RGB values:
fill(random(256),random(256),random(256));
To change the colors while the program is running, the changes must be made inside the draw() method, that will constantly loop and update the canvas. Further information about draw here I believe the following code outputs what you asked for:
int rows = 10;
int cols = 10;
int cellHeight;
int cellWidth;
void setup(){
size(500, 500);
cellHeight = height/rows;
cellWidth = width/cols;
textAlign(CENTER, CENTER);
textSize(28);
}
void draw(){
background(32);
for(int y = 0; y < rows; y++){
for(int x = 0; x < cols; x++){
//get a random ascii letter
char c = '!';
c += random(93);
//calculate cell position
int pixelX = cellWidth * x;
int pixelY = cellHeight * y;
//add half to center letters
pixelX += cellWidth/2;
pixelY += cellHeight/2;
fill(random(256),random(256),random(256));
text(c, pixelX, pixelY);
}
}
delay(100);
}

Processing(Java) to p5js - glitch effect

I'm new in p5js and i want to create a noise effect in an image with it. I create a functional sketch with Java in processing, but when i pass it to p5j something is wrong.
The image is download in the html field hwne i put , but the pixels loc staff doesn't.
Can anyone help me!!
This is my sketch:
function setup()
{
createCanvas(400,300);
img = loadImage("data/monja.jpg");
//surface.setResizable(true);
//surface.setSize(img.width, img.height);
background(0);
}
function draw()
{
loadPixels();
img.loadPixels();
for (let x = 0; x < img.width; x++)
{
for (let y = 0; y < img.height; y++)
{
let loc = x+y*width;
let c = brightness(img.pixels[loc]);
let r = red(img.pixels[loc]);
let g = green(img.pixels[loc]);
let b = blue(img.pixels[loc]);
if (c < 70){
img.pixels[loc]= color(random(255));
}
else {
img.pixels[loc] = color(r, g, b);
}
}
}
updatePixels();
//image(img, 0, 0);
}```
To modify the color of certain pixels in an image here are some things to keep in mind.
When we call loadPixels the pixels array is an array of numbers.
How many numbers each pixel gets is determined by the pixel density
If pixel density is 1 then each pixel will get 4 numbers in the array, each with a value from 0 to 255.
The first number determines the amount of red in the pixel, the second green, the third red and the fourth is the alpha value for transparency.
Here is an example that changes pixels with a high red value to a random gray scale to create a glitch effect.
var img;
var c;
function preload(){
img = loadImage("https://i.imgur.com/rpQdRoY.jpeg");
}
function setup()
{
createCanvas(img.width, img.height);
background(0);
let d = pixelDensity();
img.loadPixels();
for (let i = 0; i < 4 * (img.width*d * img.height*d); i += 4) {
if (img.pixels[i] > 150 && img.pixels[i+1] <100&&img.pixels[i+2] < 100){
let rColor = random(255);
img.pixels[i] = rColor;
img.pixels[i + 1] = rColor;
img.pixels[i + 2] = rColor;
img.pixels[i + 3] = rColor;
}
}
img.updatePixels();
}
function draw() {
image(img,0,0);
}
<script src="https://cdn.jsdelivr.net/npm/p5#1.3.0/lib/p5.js"></script>

modification in the animation of vertical lines with processing

i have modified the code for the animation of vertical lines which was given by . In the recent code I need to change the value between the two arrays of lines which are generated by the code and also make the disappearing of lines gradual. All the lines leaving or coming should have the same spacing between them. Below is the code.
//float[] linePositions = new float[10];
ArrayList<Integer> linePositions = new ArrayList<Integer>();
int lineWidth = 50;
int lineSpacing = 25;
int lineSpeed = 1;
int totalwidth;
int pixelperframe = 0;
int arraySize = 0;
void setup() {
size(640, 360);
println("Setup");
totalwidth = lineWidth+lineSpacing;
for (int i = 0; i < width; i=i +totalwidth) {
//Float value = 0 + (lineWidth+lineSpacing)*i;
linePositions.add(i);
}
arraySize = linePositions.size();
}
Boolean drawn = false;
void draw() {
println("Draw");
background(51);
//loop through the lines
//println("before Draw ka forloop"+linePositions.size());\
pixelperframe = ((lineSpeed - 10) > 1) ? (lineSpeed-10) : 1;
for (int i = 0; i < arraySize; i++) {
//println("Draw ka forloop");
rect(linePositions.get(i), 0, lineWidth, width);
int newPosition = linePositions.get(i) - pixelperframe ;
linePositions.set(i, newPosition);
//linePositions[i] -= lineSpeed;
//wrap the line
if ( linePositions.get(i) < 0) {
println("Wrapping the line");
linePositions.set(i, width);
// drawn = true;
}
}
//int temp = (width - linePositions.get(arraySize - 1)) - totalwidth;
//println(temp);
}
For the spacing between the lines to always be the same, you have to make sure that the total line spacing adds up to the total width of your screen. Right now each line takes up 75 pixels (50 for the line itself and 25 for the space after it), but your width is 640. That will always leave you with extra space, which will mess up your spacing after the lines start over.
So the easiest thing to do is to simply make your window a multiple of the line spacing. Let's go with 600, which is enough room for exactly 8 lines.
However, since you want your lines to slide off the screen, you actually need 9 lines, since you'll often see half of one line going off the screen while half of another line enters the screen. Draw some pictures to see exactly what I'm talking about
If I understand what you mean by making the lines "gradually" restart, you just have to restart them when their right side goes off the screen. In other words, when their x position is negative enough to be off the screen.
Putting it all together, it looks like this:
float[] linePositions = new float[9];
float lineWidth = 50;
float lineSpacing = 25;
float lineSpeed = 1;
void setup() {
size(600, 360);
for (int i = 0; i < linePositions.length; i++) {
linePositions[i] = (lineWidth+lineSpacing)*i;
}
}
void draw() {
background(51);
for (int i = 0; i < linePositions.length; i++) {
linePositions[i] -= lineSpeed;
rect(linePositions[i], 0, lineWidth, height);
if ( linePositions[i] < -(lineWidth+lineSpacing)) {
linePositions[i] = width;
}
}
}

animation of vertical bars using processing

I am basically trying to make a animation of vertical bars across the screen which should be equally spaced and continue until some key is pressed etc.. in the processing.org tool for animation.
I was able to get a kind of animation, but with hard coded values and had to write the same code again and again to generate the animation of bars for the whole frame/screen. I need to make it generic, so that changing the screen width or the size of the bars would not make me change the whole code but just the variables which control the parameters. Below is my code. I have written the code for three vertical bars but that needs to be done for the whole screen..
int a;
int i;
int j;
void setup() {
size(640, 360);
a = width/2;
i = 0;
}
void draw() {
background(51);
//need to avoid these repetitions each time for each bar
rect(a , 0, 25, width);
a = a - 1;
if (a < 0) {
a = width;
}
rect(i= a+50, 0, 25, width);
i = i - 1;
if (i < 0) {
i = width + a;
}
rect(j = i + 50, 0, 25, width);
j = j - 1;
if (a < 0) {
j = width + i;
}
}
It sounds like you're looking for an array.
An array is like a variable, only it can hold multiple values in its indexes. You can then use a for loop to iterate over the array and do stuff based on the values in the array.
Here's an example that uses an array to keep track of the line positions:
float[] linePositions = new float[10];
float lineWidth = 25;
float lineSpacing = 25;
float lineSpeed = 1;
void setup() {
size(640, 360);
for (int i = 0; i < linePositions.length; i++) {
linePositions[i] = width/2 + (lineWidth+lineSpacing)*i;
}
}
void draw() {
background(51);
//loop through the lines
for (int i = 0; i < linePositions.length; i++) {
//draw the line
rect(linePositions[i], 0, lineWidth, width);
//move the line
linePositions[i] -= lineSpeed;
//wrap the line
if ( linePositions[i] < 0) {
linePositions[i] = width;
}
}
}
More info on arrays can be found in the Processing reference.

Pixel reordering is wrong when trying to process and display image copy with lower res

I'm currently making an application using processing intended to take an image and apply 8bit style processing to it: that is to make it look pixelated. To do this it has a method that take a style and window size as parameters (style is the shape in which the window is to be displayed - rect, ellipse, cross etc, and window size is a number between 1-10 squared) - to produce results similar to the iphone app pxl ( http://itunes.apple.com/us/app/pxl./id499620829?mt=8 ). This method then counts through the image's pixels, window by window averages the colour of the window and displays a rect(or which every shape/style chosen) at the equivalent space on the other side of the sketch window (the sketch when run is supposed to display the original image on the left mirror it with the processed version on the right).
The problem Im having is when drawing the averaged colour rects, the order in which they display becomes skewed..
Although the results are rather amusing, they are not what I want. Here the code:
//=========================================================
// GLOBAL VARIABLES
//=========================================================
PImage img;
public int avR, avG, avB;
private final int BLOCKS = 0, DOTS = 1, VERTICAL_CROSSES = 2, HORIZONTAL_CROSSES = 3;
public sRGB styleColour;
//=========================================================
// METHODS FOR AVERAGING WINDOW COLOURS, CREATING AN
// 8 BIT REPRESENTATION OF THE IMAGE AND LOADING AN
// IMAGE
//=========================================================
public sRGB averageWindowColour(color [] c){
// RGB Variables
float r = 0;
float g = 0;
float b = 0;
// Iterator
int i = 0;
int sizeOfWindow = c.length;
// Count through the window's pixels, store the
// red, green and blue values in the RGB variables
// and sum them into the average variables
for(i = 0; i < c.length; i++){
r = red (c[i]);
g = green(c[i]);
b = blue (c[i]);
avR += r;
avG += g;
avB += b;
}
// Divide the sum of the red, green and blue
// values by the number of pixels in the window
// to obtain the average
avR = avR / sizeOfWindow;
avG = avG / sizeOfWindow;
avB = avB / sizeOfWindow;
// Return the colour
return new sRGB(avR,avG,avB);
}
public void eightBitIT(int style, int windowSize){
img.loadPixels();
for(int wx = 0; wx < img.width; wx += (sqrt(windowSize))){
for(int wy = 0; wy < img.height; wy += (sqrt(windowSize))){
color [] tempCols = new color[windowSize];
int i = 0;
for(int x = 0; x < (sqrt(windowSize)); x ++){
for(int y = 0; y < (sqrt(windowSize)); y ++){
int loc = (wx+x) + (y+wy)*(img.width-windowSize);
tempCols[i] = img.pixels[loc];
// println("Window loc X: "+(wx+(img.width+5))+" Window loc Y: "+(wy+5)+" Window pix X: "+x+" Window Pix Y: "+y);
i++;
}
}
//this is ment to be in a switch test (0 = rect, 1 ellipse etc)
styleColour = new sRGB(averageWindowColour(tempCols));
//println("R: "+ red(styleColour.returnColourScaled())+" G: "+green(styleColour.returnColourScaled())+" B: "+blue(styleColour.returnColourScaled()));
rectMode(CORNER);
noStroke();
fill(styleColour.returnColourScaled());
//println("Rect Loc X: "+(wx+(img.width+5))+" Y: "+(wy+5));
ellipse(wx+(img.width+5),wy+5,sqrt(windowSize),sqrt(windowSize));
}
}
}
public PImage load(String s){
PImage temp = loadImage(s);
temp.resize(600,470);
return temp;
}
void setup(){
background(0);
// Load the image and set size of screen to its size*2 + the borders
// and display the image.
img = loadImage("oscilloscope.jpg");
size(img.width*2+15,(img.height+10));
frameRate(25);
image(img,5,5);
// Draw the borders
strokeWeight(5);
stroke(255);
rectMode(CORNERS);
noFill();
rect(2.5,2.5,img.width+3,height-3);
rect(img.width+2.5,2.5,width-3,height-3);
stroke(255,0,0);
strokeWeight(1);
rect(5,5,9,9); //window example
// process the image
eightBitIT(BLOCKS, 16);
}
void draw(){
//eightBitIT(BLOCKS, 4);
//println("X: "+mouseX+" Y: "+mouseY);
}
This has been bugging me for a while now as I can't see where in my code im offsetting the coordinates so they display like this. I know its probably something very trivial but I can seem to work it out. If anyone can spot why this skewed reordering is happening i would be much obliged as i have quite a lot of other ideas i want to implement and this is holding me back...
Thanks,

Resources