I'd like to get the areas in pixels and the distributions of the different black objects in this image. I assume that with python (openCV or mahotas) it's possible to do it, but I don't know how.
How can one compute and find the distribution of the areas of the objects in an image with Python?
423 Views Asked by J.A AtThere are 2 best solutions below
On
Here's an alternative solution, given that your question doesn't seem that intent on using any particular tool. It uses ImageMagick which is installed on most Linux distros and is readily available for macOS and Windows. You just run the following in a Terminal window:
convert blobs.png -threshold 50% -negate \
-define connected-components:verbose=true \
-connected-components 8 info: | awk '/255,255,255/{print $4}'
Sample output follows, and it is the size (in pixels) of each blob found in the image:
19427
2317
2299
1605
1526
1194
1060
864
840
731
532
411
369
313
288
259
253
244
240
238
216
122
119
90
73
70
36
23
10
In order to better understand it, remove the awk stuff so you can see the output of "Connected Component Analysis":
convert blobs.png -threshold 50% -negate -define connected-components:verbose=true -connected-components 8 info:
Objects (id: bounding-box centroid area mean-color):
0: 675x500+0+0 341.1,251.2 301025 srgb(0,0,0)
13: 198x225+232+119 341.5,227.0 19427 srgb(255,255,255)
24: 69x62+232+347 269.4,378.9 2317 srgb(255,255,255)
22: 40x90+67+313 88.8,354.8 2299 srgb(255,255,255)
20: 55x50+121+278 153.3,299.5 1605 srgb(255,255,255)
10: 34x82+107+78 126.2,115.5 1526 srgb(255,255,255)
25: 34x47+439+350 455.4,371.5 1194 srgb(255,255,255)
16: 26x69+422+183 435.4,217.6 1060 srgb(255,255,255)
19: 27x44+231+264 243.6,284.1 864 srgb(255,255,255)
...
...
21: 5x9+0+284 1.8,288.8 36 srgb(255,255,255)
29: 6x5+57+467 59.9,468.7 23 srgb(255,255,255)
4: 6x2+448+0 450.5,0.4 10 srgb(255,255,255)
Basically, there is one line of output for each blob. That line tells you the x,y position of the top-left corner of the blob and its width and height. It also tells you the centroid, area (in the 4th column which is why I printed $4 in awk) and the colour. Note that your black blobs show up as white (255,255,255) because I inverted your image (with -negate) since ImageMagick looks for white objects on a black background.
So, if I take the line starting 13:, and draw in the rectangle containing the blob:
convert blobs.png -fill none -stroke red -draw "rectangle 232,119 430,343" result.png


I'd use scikit-image. It looks like a binary image (0s and 1s) to me, so you could use regionprops function to get a list of regionprops objects.
Regionprops ignores 0s (which is black in your case), so you might need to invert the image.