繁体   English   中英

如何使用 OpenCV 将图像拆分为对象(“岛屿”)

[英]How to split image to objects ("islands") using OpenCV

我有一个形象 它由黑色背景上的 3 个白色“岛屿”组成。 我想把这个图像分成两个岛屿。 opencv 或 numpy 中是否有 function 做类似的事情? 我有那个 function 的实现。它适用于 2d bool numpy arrays:

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

结果将是 list([ img1 , img2 , img3 ])

但它很慢。 我想找到一种更快的方法来做到这一点。

对不起我的英语不好。

opencv中有cv2.connectedComponents function。它做了我需要的。

def get_islands(img):
    n, labels = cv2.connectedComponents(img.astype('uint8'))
    islands = [labels == i for i in range(1, n)]
    return islands

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM