How to find colors of an image with p5.js?

Member

by mac , in category: Javascript , 2 months ago

How to find colors of an image with p5.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , 2 months ago

@mac 

To find the colors of an image with p5.js, you can use the loadImage() function to load an image and then use the get() function to get the color of a specific pixel in the image. Here's an example code that shows how to find the colors of an image:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
let img;

function preload() {
  img = loadImage('image.jpg');
}

function setup() {
  createCanvas(img.width, img.height);
  image(img, 0, 0);

  // Get the color of a specific pixel in the image
  let pixelColor = img.get(100, 100);
  console.log(pixelColor);

  // Loop through all pixels in the image and get their color
  for (let x = 0; x < img.width; x++) {
    for (let y = 0; y < img.height; y++) {
      let pixelColor = img.get(x, y);
      // Do something with the color
    }
  }
}


In this code, you first load an image using the loadImage() function in the preload() function. Then, in the setup() function, you create a canvas with the same dimensions as the image and draw the image on the canvas. You can use the get() function to get the color of a specific pixel in the image by passing the x and y coordinates as arguments.


You can also loop through all the pixels in the image using nested for loops and get the color of each pixel. This allows you to analyze the colors of the image or perform any manipulations based on the colors.