如何使用 OpenCV 将图像分割为对象(“岛”)
我有一个图像。它由黑色背景上的 3 个白色“岛屿”组成。我想把这个图像分成那些岛屿。 opencv 或 numpy 中是否有函数可以执行类似的操作?我有该功能的实现。它适用于 2d bool numpy 数组:
def get_island(img, x, y):
island = numpy.zeros_like(img, dtype=bool)
neibourghood = [(0, -1), (1, 0), (0, 1), (-1, 0)]
island[x, y] = True
img[x, y] = False
dots = [(x, y),]
while len(dots) > 0:
dots2 = dots
dots = []
for x, y in dots2:
for xs, ys in neibourghood:
x2, y2 = x + xs, y + ys
if 0 <= x2 < img.shape[0] and 0 <= y2 < img.shape[1]:
if img[x2, y2]:
img[x2, y2] = False
island[x2, y2] = True
dots.append((x2, y2),)
return island
def get_islands(img:numpy.ndarray) -> list: # <- that function
img = numpy.copy(img)
islands = []
while 1:
xa, ya = numpy.where(img)
if xa.shape[0] == 0: break
x, y = xa[0], ya[0]
islands.append(get_island(img, x, y))
return islands
但速度很慢。我想找到一种更快的方法来做到这一点。
对不起我的英语。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
opencv中有
cv2.connectedComponents
函数。它满足我的需要。There is
cv2.connectedComponents
function in opencv. It does what I need.