Search code examples
pythonimage-processingareazero

Calculate the area of two separate geometries in Python


I have been stumped on this problem for a while now and was wondering if anyone would be able to help. So let's say I have a binary image as shown below and I would like to count the black elements (zero). The problem is I want to know the number of elements associated with 'background' and 'trapezoid' in the middle individually, so output two values. What would be the easiest way to approach this? I have been trying to do it without using a mask but is that even possible? I have the numpy and scipy libraries if that helps.

enter image description here


Solution

  • You can use two functions from scipy.ndimage.measurements: label and find_objects.

    First you invert the array, because label function considers zero to be the background.

    inverted = 1 - binary_image_array
    

    Then you call label to find the different regions:

    labeled_array, num_features = scipy.ndimage.measurements.label(inverted)
    

    So, for this particular array, where you already know there are exactely two black blobs, you have the two regions in labeled_array.