次回11/06は、前回に引き続きWebカメラの応用実験(Webカメラを使ってArduinoを操作する)を行いたいと思います。
必要なもの:
・各自のノートパソコン
・Processingのインストール
・Webカメラ(パソコン内蔵カメラでも可)
・Arduinoボード
・USBケーブル
・ブレッドボード
・ジャンパワイヤ(オス-オス)
以下、授業内で使用したサンプル
import processing.video.*;
import processing.serial.*;
Serial myPort;
Capture video;
int w=240;//320;
int h=180;//240;
int tolerance=20;
PFont font;
color targetColor=color(255,0,0);
boolean videoImage=true;
float x;
float y;
float fx;
float fy;
int sumX,sumY;
int pixelNum;
boolean detection=false;
void setup(){
size(w, h);
smooth();
video = new Capture(this, w, h);
font=createFont("Monaco",10);
textFont(font);
noStroke();
myPort=new Serial(this,"/dev/tty.usbserial-A9005baQ",9600);
}
void draw() {
if(video.available()){
video.read();
if(videoImage){
image(video, 0, 0);
}else{
background(0);
}
detection=false;
for(int i=0;i<w*h;i++){
float difRed=abs(red(targetColor)-red(video.pixels[i]));
float difGreen=abs(green(targetColor)-green(video.pixels[i]));
float difBlue=abs(blue(targetColor)-blue(video.pixels[i]));
if(difRed<tolerance && difGreen<tolerance && difBlue<tolerance){
sumX+=(i%w);
sumY+=(i/w);
pixelNum++;
detection=true;
}
}
if(detection){
x=sumX/pixelNum;
y=sumY/pixelNum;
sumX=0;
sumY=0;
pixelNum=0;
}
}
fx+=(x-fx)*0.2;
fy+=(y-fy)*0.2;
myPort.write(int(fx));
fill(255,0,0);
ellipse(fx,fy,20,20);
fill(targetColor);
rect(0,0,10,10);
text(tolerance,20,10);
String s;
if(detection){
s="detect";
}else{
s="none";
}
text(s,40,10);
}
void mousePressed(){
targetColor=video.pixels[mouseX+mouseY*w];
//println(int(red(targetColor))+","+int(green(targetColor))+","+int(blue(targetColor)));
}
void keyPressed(){
if(key=='c'){
video.settings();
}
if(key=='v'){
if(videoImage){
videoImage=false;
}else{
videoImage=true;
}
}
if(key==CODED){
if(keyCode==LEFT){
tolerance-=1;
}
if(keyCode==RIGHT){
tolerance+=1;
}
}
}