Calculating just a specific property in regionprops python

regionprops python opencv
bwconncomp python
region.bbox python
structural_similarity skimage measure
skimage metrics
connected component analysis by scikit-learn framework
measure.label opencv
regionproperties

I am using the measure.regionprops method available in scikit-image to measure the properties of the connected components. It computes a bunch of properties (Python-regionprops). However, I just need the area of each connected component. Is there a way to compute just a single property and save computation?

There seems to be a more direct way to do the same thing using regionprops with cache=False. I generated labels using skimage.segmentation.slic with n_segments=10000. Then:

rps = regionprops(labels, cache=False)
[r.area for r in rps]

My understanding of the regionprops documentation is that setting cache=False means that the attributes won't be calculated until they're called. According to %%time in Jupyter notebook, running the code above took 166ms with cache=False vs 247ms with cache=True, so it seems to work.

I tried an equivalent of the other answer and found it much slower.

%%time
ard = np.empty(10000, dtype=int)
for i in range(10000):
   ard[i] = size(np.where(labels==0)[1])

That took 34.3 seconds.

Here's a full working example comparing the two methods using the skimage astronaut sample image and labels generated by slic segmentation:

import numpy as np
import skimage
from skimage.segmentation import slic
from skimage.data import astronaut

img = astronaut()
# `+ 1` is added to avoid a region with the label of `0`
# zero is considered unlabeled so isn't counted by regionprops
# but would be counted by the other method.
segments = slic(img, n_segments=1000, compactness=10) + 1

# This is just to make it more like the original poster's 
# question.
labels, num = skimage.measure.label(segments, return_num=True)

Calculate areas using the OP's suggested method with index values adjusted to avoid the having a zero label:

%%time
area = {}
for i in range(1,num + 1):
    area[i + 1] = np.size(np.where(labels==i)[1])

CPU times: user 512 ms, sys: 0 ns, total: 512 ms Wall time: 506 ms

Same calculation using regionprops:

%%time
rps = skimage.measure.regionprops(labels, cache=False)
area2 = [r.area for r in rps]

CPU times: user 16.6 ms, sys: 0 ns, total: 16.6 ms Wall time: 16.2 ms

Verify that the results are all equal element-wise:

np.equal(area.values(), area2).all()

True

So, as long as zero labels and the difference in indexing is accounted for, both methods give the same result but regionprops without caching is faster.

Module: measure — skimage v0.18.dev0 docs, Calculate all central image moments up to a certain order. Compute image properties and return them as a pandas-compatible table. This is a side-effect of how the input array is traversed, but can be relied upon. skimage.measure. regionprops ), then it is more efficient to pre-compute them and pass them to the inertia� import math import matplotlib.pyplot as plt import numpy as np import pandas as pd from skimage.draw import ellipse from skimage.measure import label, regionprops, regionprops_table from skimage.transform import rotate image = np.zeros((600, 600)) rr, cc = ellipse(300, 350, 100, 220) image[rr, cc] = 1 image = rotate(image, angle=15, order=0) rr, cc = ellipse(100, 100, 60, 50) image[rr, cc] = 1 label_img = label(image) regions = regionprops(label_img)

I found a way for avoiding using regionprops and computing all the properties when all we need is the area of the connected components. When the labelling of the connected component is done using the label command, we can compute the size of each component by computing the number of pixels with a given label. So, basically

labels,num=label(image, return_num=True)
for i in range(num):
    area[i]=size(np.where(labels==i)[1])

will compute the number of pixels in each connected component.

Python Examples of skimage.measure.regionprops, This page shows Python examples of skimage.measure.regionprops. centroid weighted by intensities moved only up # to a single pixel (guess centroids are already def filter_cloudmask(cloudmask, threshold=1, connectivity=1): """Filter a given :func:`skimage.measure.regionprops`: Used to calculate cloud properties. def get_cloudproperties(cloudmask, connectivity=1): """Calculate basic cloud properties from binary cloudmask. Note: All parameters are calculated in pixels!! See also: :func:`skimage.measure.label`: Used to find different clouds. :func:`skimage.measure.regionprops`: Used to calculate cloud properties. Parameters: cloudmask (ndarray): 2d binary

@optimist

Your non-regionprops method showed some inefficiencies for me. It picked up some unwanted noise and incorrectly calculated one of the shapes

import numpy as np
from skimage.measure import label, regionprops
import matplotlib.pyplot as plt

arr = np.array([[1,0,1,0,0,0,1],
                [1,1,1,0,0,0,1],
                [0,1,1,0,0,0,1],
                [0,1,1,0,0,1,1],
                [0,0,0,0,1,1,1],
                [0,0,0,1,1,1,1],
                [1,0,0,1,1,1,1],
                [1,0,0,1,1,1,1],
                [1,0,0,1,1,1,1]])

area = {}
labels, num = label(arr, return_num=True)
for i in range(num):
    print(i)
    area[i]=np.size(np.where(labels==i)[1])
    print(area[i])

plt.imshow(labels)
plt.show();

rps = regionprops(labels, cache=False)
[r.area for r in rps]

Out: [9, 24, 3]

porespy.metrics.__regionprops__ — PoreSpy documentation, All the values for a given property (e.g. 'sphericity') can be obtained as ``val but that is because they defer calculation of certain properties until they are� In addition, you can calculate area, length, perimeter, and other geometric properties on fields in attribute tables. The sections below include examples of using the field calculator. Calculations are performed using Python, SQL and Arcade. This topic focuses on Python-based Calculate Field examples.

metrics — PoreSpy documentation, This submodule contains functions for determining key metrics about an image. porespy.metrics.props_to_image (regionprops, …) the skimage version, but that is because they defer calculation of certain properties until they are accessed ,� regionprops computes the perimeter by calculating the distance between each adjoining pair of pixels around the border of the region. If the image contains discontiguous regions, regionprops returns unexpected results. This figure illustrates the pixels included in the perimeter calculation for this object.

Scikit-Image : Image Processing with Python � python-data, However, scipy tends to focus on only the most basic image processing algorithms. let's remedy that by automatically determining the threshold value ( instead of using skimage.measure contains a convenience function called regionprops (which We can also collect specific properties (for plotting, e.g.), by using a list� import matplotlib.pyplot as plt import matplotlib.patches as mpatches from skimage import data from skimage.filters import threshold_otsu from skimage.segmentation import clear_border from skimage.measure import label, regionprops from skimage.morphology import closing, square from skimage.color import label2rgb image = data. coins ()[50:-50, 50:-50] # apply threshold thresh = threshold_otsu

Measure properties of image regions, Calculate properties of regions in the image and return the data in a table. Connected components, specified as a structure returned by bwconncomp . If you specify 'basic' , then regionprops computes only the 'Area' , 'Centroid' , and� After the two commands you show, CC=bwconncomp(BW); area=regionprops(CC,'Area'); area is a struct array where area(ii).Area is the area for object ii.This corresponds to the connected component given by CC.PixelIdxList{ii}.

Comments
  • Did the results remain unchanged? If yes, I'd like to mark this as the accepted answer.
  • As long as you account for zero labels, the results are the same. I've added an expanded example with results comparison. Cheers.
  • This answer is incorrect; caching simply determines whether, once a property is asked for, it is retained in memory. No properties are pre-computed, irrespective of the value of the flag.
  • please see my answer