0
votes

I am trying to detect the level of irregularity in the perimeter of a white object in a black image. I found some good code to do it in MATLAB, but it relies on the function bwarea, which seems to be a weighted area that factors in perimeter. I am not sure what the equivalent code would be in python - would really appreciate if someone could give me an equivalent. Alternatively, if anyone knows a good metric for determining perimeter irregularity of a white object in a black image (i.e. a binary image), that would also be helpful!!

1
The MATLAB documentation gives the exact algorithm used by bwarea. - beaker

1 Answers

0
votes

Thanks for the pointer to the documentation! I've included my implementation below. I doubt it's very efficient but it worked well enough for me:

def patternScore(neighborhood):
    m_sum = 0
    m_sum = neighborhood[0,0] + neighborhood[0,1] + neighborhood[1,0] + neighborhood[1,1]
    if(m_sum == 3):
        return float(7.0/8.0)
    elif(m_sum == 0):
        return 0
    elif(m_sum == 1):
        return float(1.0/4.0)
    elif(m_sum == 4):
        return 1
    else:
        if(neighborhood[0][1] == neighborhood[0][0]):
            return .5
        elif(neighborhood[1][0] == neighborhood[0][0]):
            return .5
        else:
            return .75

def neighbors(im, i, j, d=1):
    im = np.array(im).astype(int)
    top_left = im[i-d:i+d, j-d:j+d]
    top_right = im[i-d:i+d, j:j+d+1]
    bottom_left = im[i:i+d+1, j-d:j+d]
    bottom_right = im[i:i+d+1, j:j+d+1]
    pattern = (patternScore(top_left) + patternScore(top_right) + patternScore(bottom_left) + patternScore(bottom_right))
    return pattern

def bwarea(img):
    d = 1
    area = 0
    for i in range(1,img.shape[0]-1):
        for j in range(1,img.shape[1]-1):
            area += neighbors(img,i,j)
    return area