我在图像像素分析方面遇到问题。
我正在尝试分析每个白色像素(R=255,G=255,B=255)。
问题在于这些数据的存储/读取。
for (int i = 0; i <= Map.getHeight(); i++) {
for (int j = 0; j <= Map.getWidth(); j++) {
if (Map.getColor(j, i).getBlue() == 255 && Map.getColor(j, i).getRed() == 255
&& Map.getColor(j, i).getGreen() == 255)
{
// coordsX = new HashMap<>();
coordsX.put(j, new Rectangle(j, i, 5, 5));
}
}
coordsY.put(i, coordsX);
}
System.out.println();
}
读取函数如下:
for (Entry<Integer, HashMap<Integer, Rectangle>> e : coordsY.entrySet()) {
// HashMap<Integer, Rectangle> coordsX = coordsY.get(y);
HashMap<Integer, Rectangle> coordsX = e.getValue();
if (coordsX != null) {
for (Entry<Integer, Rectangle> entry : coordsX.entrySet()) {
Rectangle rect = entry.getValue();
g.setColor(Color.red);
g.draw(rect);
if (this.car2.intersects(rect)) {
intersectsTrack = true;
}
}
}
}
问题是当我概述时:
coordsX = new HashMap<>();
就像上面做的那样,我只得到一个 y 值的所有 x 值 example .
如果我不勾勒出这条线,那就相反了。 example .
你能帮我解决这个问题吗?
亲切的问候
最佳答案
每次发现新的白色像素时,您都会创建一个新的 coordsX
。这可能不是你想要的。因此,对于每个y
,都会有一个 map coordsX
,其中只有一个条目,任何先前的条目都将被丢弃。
此外,我建议创建一个用于表示 2D 坐标的类,我们将其称为 坐标
,这样您的算法就会更容易实现。 (或者也许已经有这样的东西,例如Point
?)
class Coordinate {
private int x, y; // plus getter, setter, etc.
public int hashCode() {
return Objects.hash(x, y);
}
public boolean equals(Object obj) {
if (obj == this)
return true;
else if (!(obj instanceof Coordinate))
return false;
Coordinate that = (Coordinate) obj;
return this.x == that.x && this.y == that.y;
}
public String toString() {
return "(" + x + ", " + y + ")";
}
}
// ...
Map<Coordinate, Rectangle> coords = new HashMap<>();
for (int y = 0; y <= Map.getHeight(); y++) {
for (int x = 0; x <= Map.getWidth(); x++) {
Color color = Map.getColor(x, y);
if (color.getBlue() == 255 && color.getRed() == 255 && color.getGreen() == 255) {
Coordinate coordinate = new Coordinate(x, y);
Rectangle rectangle = new Rectangle(x, y, 5, 5);
coords.put(coordinate, rectangle);
}
}
}
for (Rectangle rectangle : coords.values()) {
g.setColor(Color.red);
g.draw(rect);
}
关于Java HashMap中Hashmap.Store所有像素坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34092551/