mousePressed() to change image on openCV

Hey, I’m just starting out with Processing!

I’m trying to make a simple ‘digital fitting room’. I’m using openCV to attach the clothes to the body (it isn’t perfect but it’s enough).

I want to change the clothes attached to the body every time the user clicks. I’ve tried using mousePressed() but I still couldn’t figure out how to do it.

Here’s my code right now.

Sorry if it’s a whole mess, I’m not too sure what I’m doing most of the time.

Thanks in advance to anyone!

import gab.opencv.*;
import processing.video.*;
import java.awt.*;

boolean hasClicked;

PImage hat;
PImage moustache;
PImage hat2;
PImage dress;

Capture video;
OpenCV opencv;

void setup() {
  size(640, 480);
  video = new Capture(this, 640/2, 480/2);
  opencv = new OpenCV(this, 640/2, 480/2);
  opencv.loadCascade(OpenCV.CASCADE_FRONTALFACE);  
  
  hat = loadImage("hat.png");
  hat2 = loadImage("hat2.png");
  moustache = loadImage("moustache.png");
  dress = loadImage("dress.png");
 
  video.start();
}

void draw() {
  
  scale(2);
  opencv.loadImage(video);

  image(video, 0, 0 );

  noFill();
  stroke(0, 255, 0);
  strokeWeight(3);
  Rectangle[] faces = opencv.detect();
  println(faces.length);

  for (int i = 0; i < faces.length; i++) {
    println(faces[i].x + "," + faces[i].y);
    image(hat,faces[i].x, faces[i].y-70, faces[i].width, faces[i].height);
    image(moustache,faces[i].x, faces[i].y+20, faces[i].width, faces[i].height);
    image(dress,faces[i].x, faces[i].y+130, faces[i].width, faces[i].height);
  }
}


void mousePressed(){
  hasClicked = true

void captureEvent(Capture c) {
  c.read();
}
1 Like

I’m not sure if I understand what your goal is. Do you want to change hat, moustache, hat2 and dress whenever the mouse is pressed?

Ah, sorry if I wasn’t too clear. I haven’t finished adding all the assets but basically what I want to do is, for example, whenever the mouse is pressed hat would turn to hat2. The same will go with the rest of the assets (perhaps dress to dress2 and so on).

1 Like

Thanks for the clarification, I see what you are trying to do know! :smile:

I would declare a new variable for each piece of clothing, which you can use to specify which kind to display:

PImage activeHat, activeMoustache, activeDress;

and initialize them like this:

void setup() {
  // ...

  activeHat = hat;
  activeMoustache = moustache;
  activeDress = dress;
  // Or you could randomize it if you want.
}

Then change your draw method to display these active images.
Now you can easily change the clothing just by assigning those variables other values:

void mousePressed() {
  activeHat = hat2;
  activeMoustache= moustache2;
  activeDress = dress2;
}

You could obviously apply a lot more customization to your mousePressed method, but this should be all you need for now. :wink:

1 Like