接着上一篇博文,先完善一下,后面一边学习一边完善,今天做到的效果图如下:
代码如下:
import KinectPV2.*;
KinectPV2 kinect2;
PImage img;
ParticleSystem ps;
Particle p ;
int offset;
float minThresh = 518;
float maxThresh = 1184;
int d;
int particleDensity;
void setup() {
size(512, 414, P3D);
frameRate(60);
kinect2 = new KinectPV2(this);
kinect2 = new KinectPV2(this);
kinect2.enableDepthImg(true);
img = createImage(kinect2.getDepthImage().width, kinect2.getDepthImage().height, RGB);
println(img.width, img.height);
kinect2.init();
ps = new ParticleSystem();
particleDensity =50;
}
void draw() {
background(255);
img.loadPixels();
//minThresh = map(mouseX,0,width,0,4500);
//maxThresh = map(mouseY,0,height,0,4500);
//println(minThresh, maxThresh);
int[] depth = kinect2.getRawDepthData();
float sumX = 0;
float sumY = 0;
float totalPixels = 0;
// image(img,0,0);
for (int x = 0; x < img.width; x++) {
for (int y = 0; y < img.height; y ++) {
offset = x + y*img.width;
d = depth[offset];
if (d> minThresh && d< maxThresh&& offset%100==0) {
//int r =int(random(0, 255)) ;
//int g =int(random(0, 255));
//int b =int(random(0, 255));
// img.pixels[offset] = color(r, g, b);
// img.pixels[offset] = color(255, 0, 150);
ps.addParticle(new PVector(x, y));
ps.run();
//ellipse(x,y,2,2);
sumX += x;
sumY += y;
totalPixels ++;
} else {
img.pixels[offset] = color(255);
}
}
}
img.updatePixels();
//image(img, 0, 0);
float avgX = sumX /totalPixels;
float avgY = sumY / totalPixels;
fill(150, 0, 255);
ellipse(avgX, avgY, 64, 64);
}
class Particle {
PVector location;
PVector velocity;
PVector acceleration;
float lifespan;
Particle(PVector l) {
// The acceleration
acceleration = new PVector(0, 0);
// circel's x and y ==> range
velocity = new PVector(0,0);
// apawn's position
location = l.copy();
// the circle life time
lifespan = 255.0;
}
void run() {
update();
display();
}
void update() {
velocity.add(acceleration);
location.add(velocity);
lifespan-=9.0;
}
boolean isDead() {
if (lifespan <= 0) {
return true;
} else {
return false;
}
}
void display() {
// border
stroke(0, lifespan);
// border's weight
// strokeWeight(0);
//noFill();
float r = random(0,255);
float g = random(0,255);
float b = random(0,255);
// random the circle's color
fill(r,g,b);
// draw circle
noStroke();
ellipse(location.x, location.y,5, 5);
}
}// A class to describe a group of Particles
// An ArrayList is used to manage the list of Particles
class ParticleSystem {
ArrayList<Particle> particles;
PVector origin;
ParticleSystem() {
particles = new ArrayList<Particle>();
}
void addParticle(PVector position) {
origin = position.copy();
particles.add(new Particle(origin));
}
void run() {
for (int i = particles.size()-1; i >= 0; i--) {
Particle p = particles.get(i);
p.run();
if (p.isDead()) {
particles.remove(i);
}
}
}
}