我会提供一个相当天真的方式来解决问题(不完全实现特德,只是让你明白) 有一个所有矩形的列表List<Rectangle> mazeRectangles
。所有矩形将被存储在这里..当然,图像BufferedImage image;
现在我们将遍历所有图片,直到找到一个具有正确颜色的图片 每当我们找到一个矩形时,我们将跳过矩形宽度的所有x值..
//iterate over every pixel..
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
//check if current pixel has maze colour
if(isMazeColour(image.getRGB(x, y))){
Rectangle rect = findRectangle(x, y);
x+=rect.width;
}
}
}
您的检查色法:
public boolean isMazeColour(int colour){
// here you should actually check for a range of colours, since you can
// never expect to get a nicely encoded image..
return colour == Color.RED.getRGB();
}
有趣的部分是findRectangle
方法.. 我们看看是否已经有一个Rectangle
包含我们的坐标。如果是,返回它,否则创建一个新的Rectangle
,将其添加到列表并返回它。 如果我们必须创建一个新的Rectangle
,我们将首先检查它的宽度。关于这个恼人的部分是,你仍然必须检查每个像素为矩形的休息,因为你可能有一个这样的配置:
+++++++
+++++++
###
###
其中#
和+
是单独的盒子。因此,我们首先找到宽度:
public Rectangle findRectangle(int x, int y){
// this could be optimized. You could keep a separate collection where
// you remove rectangles from, once your cursor is below that rectangle
for(Rectangle rectangle : mazeRectangles){
if(!rectangle.contains(x, y)){
return rectangle;
}
}
//find the width of the `Rectangle`
int xD = 0;
while(x+xD < width && isMazeColour(image.getRGB(x+xD+1, y))){
xD++;
}
int yD = 0; //todo: find height of rect..
Rectangle toReturn = new Rectangle(x, y, xD, yD);
mazeRectangles.add(toReturn);
return toReturn;
}
我没有落实yD
的一部分,因为它是一个有点乱,我有点懒,但你需要遍历y和检查每一行(所以两个嵌套循环)
请注意,此算法可能导致重叠Rectangle
s。如果您不想要,那么在找到xD
时,检查每个像素是否已包含在Rectangle
中。只要您不在另一个Rectangle
内,就只需展开xD
即可。
另一件事:由于红色和蓝色之间的颜色插值,最终可能会在矩形边界出现奇怪的人为现象。也许你想检查矩形是小(像只有1像素宽),并摆脱它们。
jpg是这个问题的错误编码! jpg的目的是用于照相机拍摄的照片,因为它会导致两种颜色混合在一起的很多丑陋的噪音!请考虑使用PNG为您的问题! –
@神秘哦确定会做。谢谢!我不知道我对摄影和东西没什么兴趣。修正了问题主体也。 –
当然。看看这个关于维基百科的部分,看看当你使用jpg时发生了什么,你不应该使用它:https://en.wikipedia.org/wiki/Wikipedia:Preparing_images_for_upload#Do_not_save_diagrams_as_JPEG这将成为一个严重的问题, ) –