我需要创建一个处理图像中所有像素的函数,并为每个像素使用洪流填充来查找“区域”(具有相同颜色的点的列表)。如果该区域大于某个变量,则该区域将被添加到区域列表中。但是,我一直在function ()函数中遇到一个问题。在通过第一个像素后,我一直得到一个无限循环。
我认为错误在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).
*/ 发布于 2020-04-19 16:25:30
For循环是有限的--除非您这样做,否则不会无限期地循环,而且在您的代码中,一切都很好,,除了,您有4个for循环,它们在计算上非常任务处理。
想象一下在1000×1000 img中循环:
你可以从here的方程中得到一些想法。
我建议尝试一个小映像,以确保代码工作,或者找到一个替代的解决方案,而不是嵌套循环。
https://stackoverflow.com/questions/61306046
复制相似问题