英文:
Finding a square in a blank image
问题
让我们假设我有一张 JPG 图片,除了一个随机放置的绿色填充正方形外,整张图片都是白色。该正方形的边长在 20 到 30 像素之间。
我想编写一个 Java 程序来找到这个正方形的确切中心。我知道肯定有一种快速的方法可以做到这一点。有任何想法吗?
英文:
Let's say I have a JPG image that's completely white except for a green filled in square that's placed randomly. The square has equal side lengths of between 20 and 30 pixels.
I'd like to write a Java program to find the exact center of this square. I know there must be a way to do this extremely fast. Any ideas?
答案1
得分: 2
感谢所有帮助的人。您的评论非常有用。
我发现最有效的方法只是使用一种准蛮力的方法。我在x和y方向都以30个像素的步长遍历像素网格。我要搜索的图像大小约为2k x 2k,所以这很快。一旦我找到一个像素,我只需在其周围创建一个边长为30像素的邻域。这样我可以精确找到正方形的位置。
还有两个好处。我发现由于生产者的舍入误差,许多像素几乎是正确的颜色。我还能够看到正方形的每一边都是精确的30个像素。如果不是这样,我就知道生产过程有问题。
在实际应用中,这段代码比我想象的要快得多-没有必要尝试优化。
英文:
Thanks to everyone who helped. Your comments were useful.
I found that the most efficient way to do this was to just use a quasi-brute force method. I walk the pixel grid with a step of 30 pixels in both x and y direction. The images I'm searching ar around 2k X 2k, so this is pretty quick. Once I find one pixel, I just create a neighborhood around it that's 30 pixes in each direction. This way I can find exactly where the square is.
Two more benefits. I did find that many pixels were almost the correct color due to roundoff error from the producer. I was also able to see that the squares were exactly 30 pixels on each side. If they aren't, I know there's a problem with the process that producces it.
In actual practice, this code is far faster than I would have imagined - no need to try and optimize.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论