有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在图像中查找白色矩形

我试图在图像中找到一个白色的矩形。矩形的大小是固定的。这就是我目前的想法:

BufferedImage bImage = bufferedImage;
int height = bufferedImage.getHeight(); //~1100px
int width = bufferedImage.getWidth(); //~1600px
int neededWidth = width / 2; 
int neededHeight = 150;
int x = 0;
int y = 0;
boolean breaker = false;
boolean found = false;
int rgb = 0xFF00FF00;
int fx, fy;

fx = fy = 0;
JavaLogger.log.info("width, height: " + w + ", " + h);
while ((x != (width / 2) || y != (height - neededHeight)) && found == false) {
for (int i = y; i - y < neededHeight + 1; i++) {
    for (int j = x; j - x < neededWidth + 1; j++) { //Vareetu buut, ka +1 vajadziigs
        //JavaLogger.log.info("x,y: " + j + ", " + i);
        long pixel = bImage.getRGB(j, i);
        if (pixel != colorWhite && pixel != -1) {
            //bImage.setRGB(j, i, rgb);
            //JavaLogger.log.info("x,y: " + (j+x) + ", " + (i+y));
            breaker = true;
            break;

        } else {
            //bImage.setRGB(j, i, 0xFFFFFF00);
        }
        //printPixelARGB(pixel);
        if ((i - y == neededHeight-10) && j - x == neededWidth-10) {
            JavaLogger.log.info("width, height: " + x + ", " + y + "," + j + ", " + i);
            fx = j;
            fy = i;
            found = true;
            breaker = true;
            break;
        }
    }
    if (breaker) {
        breaker = false;
        break;
    }

}

if (x < (width / 2)) {
    x++;
} else {
    if (y < (height - neededHeight)) {
        y++;
        x = 0;
    } else {
        break;
    }
  }
//JavaLogger.log.info("width, height: " + x + ", " + y);
}

if (found == true) {

    for (int i = y; i < fy; i++) {
        for (int j = x; j < fx; j++) {
            bImage.setRGB(j, i, 0xFF00FF3F);
        }

    }

}
JavaLogger.log.info("width, height: " + w + ", " + h);

如果我需要的矩形接近(0;0)的开头,那么这就行了,但是随着它越来越远,性能会严重下降。我在想,是否有什么可以做的

例如,这个搜索花费了将近8秒,这相当多。 One of searches 我在想,这完全可以更有效地完成。也许有什么发现?读过它,但我不知道如何应用它

另外,我对Java和图像处理都是新手,所以非常感谢您的帮助


共 (1) 个答案

  1. # 1 楼答案

    我不是专家,但我认为代码不是问题所在——你需要改变你的算法。首先,我会在2d平面上递归搜索一个白色像素,比如:

    FindHitePixel(方形){ 看看“正方形”中间的像素——如果它是白色的,则返回它,否则: FindHitePixel(正方形右上角) FindHitePixel(正方形左上角) FindHitePixel(正方形右下角四分之一) FindHitePixel(正方形左下四分之一) }

    找到白色像素后,试着从中上下左右移动,以找到形状上的边界。如果这是一个给定的,只有矩形-你的任务完成了。如果可能有其他形状(三角形、圆形等),您需要在此处进行验证