java - 包含在大图功能中的小图不起作用
问题描述
我试图为此编写简单的解决方案,它试图匹配第一个索引,然后更深入。
但我得到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;
}
解决方案
您对子图像的搜索已关闭。您通过使用 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;
}
推荐阅读
- android - How to write a query to get data and skip 4 first letters on special records in sql
- java - 已弃用 Nashorn 的建议
- python - Python def main(req: func.HttpRequest) -> func.HttpResponse: 是什么意思?
- javascript - 在 JS 中关闭和链接函数调用 - 如何检查最后一次调用?
- netlogo - 有没有办法通过代码隐藏界面小部件?
- reactjs - 关注包大小,使用 React 中的动态 Material-UI 图标发出警告
- java - Java Regex - 用单个美元捕获字符串,但不是当它有两个连续的
- database - 在 kotlin 中搜索 sqlite 数据库的问题
- php - 我已经编写了这个 php 脚本,但名为“add_comment”的文件中的条件没有显示在浏览器中,即使它是真的
- html - Zurb Foundation 顶栏的中心元素