【问题标题】:ImageMagick or another approach: How to find the coordinates of the centre of an object in an image?ImageMagick 或其他方法:如何在图像中找到对象中心的坐标?
【发布时间】:2021-08-11 01:35:58
【问题描述】:

我正在尝试在图像(杯子)中找到对象的坐标。

我最终需要得出的信息是 x、y、宽度和高度 - 其中 x 和 y 应该是包含杯子(而不是左上角)的矩形的中心,宽度和高度应该是相对于图像宽度和高度的浮点值(从 0.0 到 1.0)。

我尝试安装 ImageMagick,加载图像,然后在 cmd 中运行以下命令:

magick image1.jpg -define connected-components:verbose=true -connected-components 8 -auto-level image1.jpg

我收到错误:ma​​gick: too many objects `image1.jpg' @ error/vision.c/ConnectedComponentsImage/437。

有谁知道如何解决这个问题,或者任何其他相对简单的方法来找到所需的坐标?

【问题讨论】:

  • 为了使用连接组件,您需要了解如何从背景中分割您的杯子对象(前景)并制作二值图像。不幸的是,您的对象与背景颜色相同。所以通过简单的图像处理很难做到这一点。您将需要一种 AI/深度学习方法,例如 remove.bg 如果您可以使用它来将前景与背景分开,那么 -connected-components 可以告诉您您想要什么。但是杯子的宽度和高度怎么能在 0 到 1 的范围内。这是相对于输入大小的分数吗?
  • 我猜是这样。事实上,我正在按照github.com/AlexeyAB/darknet/tree/… 上的说明使用 YOLO 版本 2 训练我的自定义对象。更具体地说,那些:“为每个 .jpg-image-file 创建 .txt-file - 在同一目录中并使用同名,但扩展名为 .txt,并放入文件:此图像上的对象编号和对象坐标,对于新行中的每个对象:"
  • 在下面查看我的答案,其中包含移除背景后连接组件的示例。

标签: image imagemagick coordinates


【解决方案1】:

很遗憾,您的对象与背景颜色相同。所以通过简单的图像处理很难做到这一点。您需要一种 AI/深度学习方法,例如 http://remove.bg

所以我使用了http://remove.bg 来执行此操作,但请注意 remove.bg 将图像缩小了一点。

从中我提取了 alpha 通道:

convert mug.png -alpha extract mug_alpha.png

WxH=`convert mug_alpha.png -format "%wx%h" info:`
W=`echo $WxH | cut -dx -f1`
H=`echo $WxH | cut -dx -f2`

bbox=`convert mug_alpha.png \
-type bilevel \
-define connected-components:mean-color=true \
-define connected-components:exclude-header=true \
-define connected-components:verbose=true \
-define connected-components:keep-top=1 \
-connected-components 4 \
null: | grep "gray(255)" | awk '{print $2}' | tr "x" "+"`
wd=`echo $bbox | cut -d+ -f1`
ht=`echo $bbox | cut -d+ -f2`
xoff=`echo $bbox | cut -d+ -f3`
yoff=`echo $bbox | cut -d+ -f4`

xcenter=`convert xc: -format "%[fx:$xoff + $wd/2]" info:`
ycenter=`convert xc: -format "%[fx:$yoff + $ht/2]" info:`
width=`convert xc: -format "%[fx:$wd/$W]" info:`
height=`convert xc: -format "%[fx:$ht/$H]" info:`
echo "xcenter=$xcenter, ycenter=$ycenter, width=$width, height=$height"

xcenter=277, ycenter=260, width=0.563433, height=0.60515


left=$xoff
top=$yoff
right=$((xoff+wd-1))
bottom=$((yoff+ht-1))
convert mug.png -fill none -stroke red -draw "rectangle $left,$top $right,$bottom" -alpha off mug_box.png
convert mug_alpha.png -fill none -stroke red -draw "rectangle $left,$top $right,$bottom" -alpha off mug_alpha_box.png

【讨论】:

  • 只是一个澄清的问题,你在cmd中运行代码吗?
  • 这是在命令行模式下运行的。语法是 Unix(Linux、Max OSX、Windows 10 Unix)。 Windows DOS 脚本会有所不同。
  • 非常感谢。我自己正在使用 Windows DOS,但会尝试搜索类似的脚本。再次感谢!
猜你喜欢
  • 2020-11-12
  • 1970-01-01
  • 2014-10-27
  • 1970-01-01
  • 2019-04-26
  • 2019-05-03
  • 1970-01-01
  • 2022-01-26
  • 1970-01-01
相关资源
最近更新 更多