什么是一个高效的算法找出二进制图像形状的数量?是一个、高效、算法、形状

2023-09-11 06:02:16 作者:上帝的宠儿

对于二进制图像,我感兴趣的方式来有效地计算单个数量形状present的形象。也作为相邻的问题,人们如何可以适应每个形状是​​present图像中的正方形?

For a binary image, I am interested in a way to efficiently count the number of individual shapes present in the image. Also as an adjacent question, how can one fit each shape that is present in the image in a square?

伪code是最欢迎的。

Pseudocode is most welcome.

推荐答案

我不能回答下半年,但如果上半年定义了一个形为某种颜色的连续像素,这是我做的。保持一个数组为整个图像,指示哪些像素已经被看到。 (一个布尔值[,]会做的伎俩,在C#中-speak。)

I can't answer the second half, but if the first half defines a "shape" as contiguous pixels of a certain color, here's what I do. Maintain an array for the whole image, indicating which pixels have been "seen". (A bool[,] would do the trick, in C#-speak.)

然后开始遍历每个像素。如果它被视为已,跳过它。

Then begin iterating over each pixel. If it's been seen already, skip it.

否则,如果它没有被看到和它的非形状的颜色,标记它看到的,继续前进。

Otherwise, if it's not yet been seen and it's the "non-shape" color, mark it seen and move on.

否则,它并没有被看到和是形状。从这里,蜘蛛在每四个罗盘方向。如果你达到一个看到像素,停止并折回(这$ P $发生pvents一个无限循环)。如果该像素是所述非形状的颜色,标记看到的像素,立即停止。否则,该像素是一个形状的颜色。马克看到它并把它添加到任何形定义的数据,你正在建立。

Otherwise, it hasn't been seen and is a shape. From here, spider out in each of the four compass directions. If you reach a seen pixel, stop and turn back (this prevents an infinite loop from occurring). If the pixel is the non-shape color, mark the pixel seen and stop immediately. Otherwise, the pixel is a shape color. Mark it seen and add it to whatever "shape definition" data you are building up.

在此过程完成后,你已经发现了一个形状。它存储在某处,并继续搜索。所有在该形状像素的现在应标记为可见,并将不再由该算法可以考虑

Once this process completes, you have discovered one shape. Store it somewhere, and continue searching. All of the pixels in that shape should now be marked seen, and will no longer be considered by the algorithm.

该算法的形状发现一旦形状颜色的像素已经找到本质上是递归的,而对于大型的形状可能会溢出堆栈。它可适当使用基于堆的堆实现执行整个形状搜索。

This algorithm for shape-discovery once a shape-color pixel has been located is inherently recursive, and for large shapes may overflow the stack. It may be appropriate to use a heap-based stack implementation to perform the entire shape search.

(如果考虑对角相邻足以两种形状链接成一个,只需搜索所有八个相邻像素,而不是仅仅四个horizo​​ntally-和垂直相邻的像素。)

(If you consider diagonally-adjacent pixels enough to link two shapes into one, simply search all eight adjacent pixels instead of just the four horizontally- and vertically-adjacent ones.)