1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Algorithms to fill in islands within lakes Python

Discussão em 'Python' iniciado por Stack, Outubro 7, 2024 às 01:52.

  1. Stack

    Stack Membro Participativo

    I have an ndarray where each cell is either land (1) or water (0). In this ndarray, the background and border is all land (1), and there are lakes within. Some of these lakes have islands within them. Here, an island is some connected amount of land pixels contained entirely within water. Is there an algorithm I can use to automatically change the value of any island to '0', such that all islands are completely filled in with water, while ignoring the background uncontained land?

    I have tried a few dfs based approaches so far, but my recursion is very rusty. I have written some code that tries to classify pixels as island land or not. It does this by recursively iterating on land pixels until it is confirmed they are completely surrounded by water, the recursion then unfolds and ideally yields "True" for each of these island land pixels. I think the issue lies with my base cases being wrong. I think the problem is in the "#has been visited and is land returns true" step. My vision is that once we hit an island, the recursive iterations stemming from that first island pixel will result in an "Inside" classification if and only if the last cell checked is surrounded totally by water and already visited land. I also want to make any land cells on the border automatically return false since I do not care about islands that extend off screen. The code is as follows:

    #1 is water, 0 is land def isInside(img,x,y): #img[:][:][1] is an array the same size of img where 0 is unvisited and 1 is visited dim = img[:,:,0].shape

    #if its outside the border, return false
    if(x<0 or x>=dim[1] or y<0 or y>=dim[0]):
    return False

    #has been visisted and is land returns true
    if(img[y][x][1] == 1 and img[y][x][0] == 0):
    return True

    #is water is true
    if (img[y][x][0] == 1):
    #mark visisted
    img[y][x][1] = 1
    return True

    #if its land and on the border return false
    if ((x==0 or x == dim[1]-1 or y == 0 or y == dim[0]-1) and (img[y][x][0] == 0)):
    img[y][x][1] = 1
    return False

    #is land and unvisited
    if img[y][x][0] == 0:
    #mark visited
    img[y][x][1] = 1
    #if all adjacent nodes are water or also inside land, return true
    if(isInside(img,x+1,y) and
    isInside(img,x-1,y) and
    isInside(img,x,y+1) and
    isInside(img,x,y-1)):
    return True
    return False


    I used a few artificial arrays I made, as well as my actual Sentinel image itself, however, the results are wonky. Any help is very appreciated.

    Continue reading...

Compartilhe esta Página