简体   繁体   中英

Eliminating number of connected pixels with ratio of area smaller than a treshold python

I was looking to the following example in this question: Eliminating number of connected pixels smaller than some specified number threshold which is very close to what I need.

However, the analysis there is based oly in the number of connected pixels, let's say that now I want to remove together with the areas below a certain amount of pixels also the areas which have an aspect ration different than a "square".

For instance in the following image (left panel) example output let's say I have the red line which is 1900 pixels this means that using the treshold

# now remove the labels
for label,size in enumerate(label_size):
    if size < 1800:
        Z[Zlabeled == label] = 0

the red line won't be eliminated. But if now I increase the threshold (let's say to 2000), it may happen that I eliminate also the big two figures on the right panel which is my desired output. How do I need to modify the code to consider also the aspect ratio of the connected components?

Thanks in advance:

A possible solution is using the connected component analysis done in this way

from scipy.ndimage.measurements import label
structure = np.ones((3, 3), dtype=np.int)


labeled, ncomponents = label(Z, structure)



indices = np.indices(Z.shape).T[:,:,[1, 0]]





for i in range(1,ncomponents):
    pixelcount = (np.sum(labeled==i))

    xs = indices[labeled==i][:,0]
    ys = indices[labeled==i][:,1]
    area = (np.max(xs)-np.min(xs)+2)*(np.max(ys)-np.min(ys)+1)
    if (pixelcount/area<1):
        pass
        labeled[labeled==i] = 0

plt.figure(1)
plt.imshow(labeled,cmap='jet')

where at the end I check the ratio between the pixel in a given connected area divided by the area pixelcount/area so in that way one can control the ration between pixels and total area

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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