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

问题描述 投票:0回答:2

我想得到像素区域和这个图像中不同黑色物体的分布。我假设使用python(openCV或mahotas)可以做到这一点,但我不知道如何做。

enter image description here你能帮帮我吗?

python opencv image-processing area mahotas
2个回答
2
投票

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

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


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}'

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

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的东西,以便您可以看到“连接组件分析”的输出:

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列,这就是为什么我在$4打印awk)和颜色。请注意,您的黑色斑点显示为白色(255,255,255)因为我将图像反转(使用-negate),因为ImageMagick在黑色背景上查找白色对象。

所以,如果我从13:开始行,并在包含blob的矩形中绘制:

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

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.