我使用wand 完成此操作 - 它源自 ImageMagick。它有一个skeletonise 方法和“Hit and Miss Morphology”,用于查找特定形状,例如线端或连接点。
Anthony Thyssen here 进行了精彩的讨论,但如果我可以总结一下,您在尝试查找行端时正在寻找以下形状:
在寻找路口时:
黑色方块表示图像在该位置必须是黑色的,并且在代码的内核中表示为零。白色方块意味着图像在该位置必须是白色的,并且在代码的内核中表示为那些。空白方块表示我们“不关心”该位置有什么,并在代码中表示为破折号(减号)。
代码如下所示:
#!/usr/bin/env python3
import numpy as np
from wand.image import Image
# Use 'wand' to:
# 1 skeletonize
# 2 find line-ends using Top-Hat Morphology
# 3 find line-junctions using Top-Hat Morphology
with Image(filename='Q4J0l.png') as img:
# Skeletonize
img.morphology(method='thinning',
kernel='skeleton',
iterations=-1)
img.save(filename='DEBUG-skeleton.png')
# Find line-ends using Top-Hat Morphology
# There are two kernels here, separated by a semi-colon
# Each is rotated through 90 degress to form all 4 orientations
# The first 3x3 kernel is the one tinted red in the diagram above.
# The second 3x3 kernel is the one tinted green in the diagram above
lineEnds = """
3>:
0,0,-
0,1,1
0,0,-;
3>:
0,0,0
0,1,0
0,0,1
"""
# Clone the original image as we are about to destroy it
with img.clone() as endsImage:
endsImage.morphology(method='hit_and_miss', kernel=lineEnds)
endsImage.save(filename='DEBUG-ends.png')
# Find line-junctions using Top-Hat Morphology
# There are three kernels here, separated by a semi-colon
# Each is rotated through 90 degress to form all 4 orientations
# The first 3x3 kernel is the one tinted yellow in the diagram above
# The second 3x3 kernel is the one tinted magenta in the diagram above
# The third 3x3 kernel is the one tinted cyan in the diagram above
lineJunctions = """
3>:
1,-,1
-,1,-
-,1,-;
3>:
-,1,-
-,1,1
1,-,-;
3>:
1,-,-
-,1,-
1,-,1
"""
# Clone the original image as we are about to destroy it
with img.clone() as junctionsImage:
junctionsImage.morphology(method='hit_and_miss', kernel=lineJunctions)
junctionsImage.save(filename='DEBUG-junctions.png')
调试图像如下:
调试骨架
调试行尾
调试连接
使用 ImageMagick 在终端中实际上要简单得多:
magick Q4J0l.png -morphology Thinning:-1 Skeleton skeleton.png
magick skeleton.png -morphology HMT lineends ends.png
magick skeleton.png -morphology HMT linejunctions junctions.png
或者您可以在一个命令中生成所有 3 个图像:
magick Q4J0l.png \
-morphology Thinning:-1 Skeleton -write S.png \
\( +clone -morphology HMT lineends -write E.png +delete \) \
-morphology HMT linejunctions J.png