首页 > 解决方案 > 包含在大图功能中的小图不起作用

问题描述

我试图为此编写简单的解决方案,它试图匹配第一个索引,然后更深入。

但我得到true了我不应该得到的时候,我找不到原因。

这是我的代码(Java):

boolean contains(BufferedImage img, BufferedImage subImg, int[] coordinates){
    boolean result = false;
    int verticalLimit = img.getWidth() - subImg.getWidth();
    int horizontalLimit =img.getHeight() - subImg.getHeight();

    for (int i = 0; i <= horizontalLimit; i++) {
        for (int j = 0; j <= verticalLimit; j++) {
            if(img.getRGB(j, i) == subImg.getRGB(0, 0)){
                result = true;
                coordinates[0] = j; // stores the first indices for self use
                coordinates[1] = i;
                for (int k = i; k < subImg.getHeight() && result; k++) {
                    for (int l = j; l < subImg.getWidth() && result; l++) {
                        if(img.getRGB(l, k) != subImg.getRGB(l, k)){
                            result = false;
                        }
                    }
                }
                if(result) return result;
            }
        }
    }
    return result;
}

标签: java

解决方案


您对子图像的搜索已关闭。您通过使用 k,l 进行索引,我已更改为 0 并使用 k,l 作为 i,j 的偏移量,从而跳到子图像中。还可以使用标记中断来保持“找到”状态。如果所有像素都匹配,则到达循环的末尾并返回true,否则它会中断并再次尝试,直到尝试所有可能的位置,如果没有找到则返回false。

static boolean contains(BufferedImage img, BufferedImage subImg, int[] coordinates) {
    int verticalLimit = img.getWidth() - subImg.getWidth();
    int horizontalLimit = img.getHeight() - subImg.getHeight();

    for (int i = 0; i <= horizontalLimit; i++) {
        for (int j = 0; j <= verticalLimit; j++) {
            subSearch:
            for (int k = 0; k < subImg.getHeight(); k++) {
                for (int l = 0; l < subImg.getWidth(); l++) {
                    if (img.getRGB(l + j, k + i) != subImg.getRGB(l, k)) {
                        break subSearch;
                    }
                }
                if (k==subImg.getHeight()-1){
                    coordinates[0] = j;
                    coordinates[1] = i;
                    return true;
                }
            }

        }
    }
    return false;
}

推荐阅读