如何使用Python计算并找到图像中对象区域的分布?

时间:2019-01-08 15:42:13

标签: python opencv image-processing area mahotas

我想获取此图像中以像素为单位的面积以及不同黑色对象的分布。我认为使用python(openCV或mahotas)可以做到这一点,但是我不知道怎么做。

enter image description here 你能帮我吗?

2 个答案:

答案 0 :(得分:2)

我会使用scikit-image。对我来说,它看起来像一个二进制图像(0和1),因此您可以使用regionprops函数来获取regionprops对象的列表。

Regionprops忽略0(在您的情况下为黑色),因此您可能需要反转图像。

答案 1 :(得分:2)

这是一个替代解决方案,因为您的问题似乎并不打算使用任何特定工具。它使用 ImageMagick ,它已安装在大多数Linux发行版中,并且可立即用于macOS和Windows。您只需在“终端”窗口中运行以下命令即可:

convert blobs.png -threshold 50% -negate     \
   -define connected-components:verbose=true \
   -connected-components 8 info: | awk '/255,255,255/{print $4}'

随后是示例输出,它是图像中找到的每个斑点的大小(以像素为单位):

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

为了更好地理解它,请删除awk内容,以便查看“ 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)

基本上,每个Blob都有一行输出。该行告诉您Blob左上角的x,y位置及其宽度和高度。它还告诉您质心,区域(在第四列中,这就是为什么我在$4中打印awk的原因和颜色。请注意,您的黑色斑点显示为白色(255,255,255),因为 ImageMagick 在黑色背景上寻找白色物体时,我用-negate反转了图像。

因此,如果我以13:开头的行,并绘制包含斑点的矩形​​:

convert blobs.png -fill none -stroke red -draw "rectangle 232,119 430,343" result.png

enter image description here