java - 使用 Flood FIll 在图像上查找相似颜色的区域
问题描述
我需要创建一个处理图像中所有像素的函数,并为每个像素使用洪水填充来查找“区域”(具有相同颜色的点列表)。如果区域大于某个变量,则该区域将被添加到区域列表中。但是,我在 findregions() 函数中一直遇到问题。通过第一个像素后,我不断得到一个无限循环。
我认为错误在我的 toVisit 数组列表的第三个 for 循环中,但我不确定错误是什么。
/**
* Sets regions to the flood-fill regions in the image, similar enough to the trackColor.
*/
public void findRegions(Color targetColor) {
// TODO: YOUR CODE HERE
for (int y= 0; y < image.getHeight(); y++){ // Loop over all the pixels
for (int x = 0; x < image.getWidth(); x++){
Color c = new Color(image.getRGB(x, y));
if (visited.getRGB(x, y) == 0 && colorMatch(c, targetColor )){ //Checks if pixel is unvisited and of the same color
//start a new region
Point point = new Point(x, y);
ArrayList<Point> region = new ArrayList<>(); // starts a new region
ArrayList<Point> toVisit = new ArrayList<>(); // Keeps track of what pixels need to be visited
toVisit.add(point); // Initially you just need to visit current point
for (int i = 0; i < toVisit.size(); i++){ //As long as there's a pixel that needs to be visited
region.add(toVisit.get(i)); //add it to the region
Point current = toVisit.get(i);
int cx = (int)current.getX();
int cy = (int)current.getY();
//Loop over all current pixels eight neighbors
for (int ny = Math.max(0, cy-1); ny < Math.min(image.getHeight(), cy+1); ny++) {
for (int nx = Math.max(0, cx-1); nx < Math.min(image.getWidth(), cx+1); nx++) {
Color cn = new Color(image.getRGB(nx, ny));
Point new_point = new Point(nx, ny);
//if neighbor is the correct color
if (colorMatch(cn, targetColor)) {
toVisit.add(new_point); //add it to the list of pixels to be visited
}
}
}
visited.setRGB(x, y, 1);
}
toVisit.remove(point);
if (region.size() >= minRegion){ //if region is big enough, we add it to the regions ArrayList
regions.add(region);
}
}
}
}
}
/**
* Tests whether the two colors are "similar enough" (your definition, subject to the maxColorDiff threshold, which you can vary).
*/
解决方案
For
循环是有限的,除非你这样做,否则它们不会无限循环,并且在你的代码中一切都很好,除了你有4 个 for
循环,这在计算上是相当有任务的。
想象一下循环播放 1000 x 1000 的图像:您可以通过这里
的等式获得一些想法。
我建议尝试使用小图像以确保代码正常工作或找到嵌套循环以外的替代解决方案。
推荐阅读
- oracle - 需要oracle sql查询table1中的每一个Column A条目,根据table1中row的创建时间识别table1的最新Column B值
- c# - ASP.Net Web 窗体 Active Directory 身份验证
- date - Power BI 中客户级别的当前月/年差异
- php - nginx:连接到上游时连接()失败(111:连接被拒绝)-更新nginx后-
- javascript - 将自定义组件注入到子节点的命名槽中
- pdf - 为什么在将某些 PDF 包含到输出 PDF 中时出现失真,而在其他 PDF 中不包含?
- visual-studio - 如何使用向下箭头键在组合框中选择索引?
- testing - 使用 Google Pubsub 模拟器时等待消息被确认?
- sql - x[[jj]][iseq] <- vjj 中的 Kmodes 函数错误:替换的长度为零
- spring-boot - 如何更改有关 LocalDateTime 的 WebClient 行为?