我在sketch中编写了以下Processing,它扫描图像,并将每个黑色像素的坐标存储到两个ArrayLists - xList和yList中。它当前打印出坐标,但现在我需要将这些ArrayLists发送到Arduino,并让Arduino将它存储在自己的两个数组(或一个2D数组)中。我遇到的问题是,当xList中的数据结束时,无法告诉Arduino,并且yList中的数据开始,因为ArrayLists中没有预定义数量的元素。
import javax.swing.*;
PImage img;
//Threshold determines what is considered a "black" pixel
//based on a 0-255 grayscale.
int threshold = 50;
void setup() {
// File opener
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (file.getName().endsWith("jpg")) {
img = loadImage(file.getPath());
if (img != null) {
size(img.width,img.height);
image(img,0,0);
}
} else {
println("Please select a .jpg image file.");
}
}
//I added noLoop() here, because the program would output
//the coordinates continuously until it was stopped.
noLoop();
}
void draw() {
//Here it scans through each pixel of the image.
ArrayList xList = new ArrayList();
ArrayList yList = new ArrayList();
for (int ix = 0; ix < img.width; ix++) {
for (int iy = 0; iy < img.height; iy++) {
//If the brightness of the pixel at (ix,iy) is less than
//the threshold
if (brightness(get(ix,iy)) < threshold) {
//Add ix, and iy to their respective ArrayList.
xList.add(ix);
yList.add(iy);
}
}
}
//Print out each coordinate
//For this statement, I use xList.size() as the limiting
//condition, because xList and yList should be the same size.
for (int i=0; i<xList.size(); i++) {
println("X:" + xList.get(i) + " Y:" + yList.get(i));
}
}
答案 0 :(得分:0)
由于已知两个数组的大小相同,而不是发送整个X列表,然后发送整个Y列表,您可以发送一个x然后一个y然后下一个x然后发送下一个y ...
在Arduino方面,你会将收到的第一个数字放入x数组,然后将第二个数字放入Y数组,第三个放入X,第四个放入Y等......
在Arduino上要注意的一点是,因为它在C ++中没有对数组进行边界检查,所以当向其添加新数据时数组也不会增长。您必须确保使用足够的存储空间初始化数组以适应所有坐标。