如何将提取的矩形WxH+X+Y尺寸位置标注到对应矩形内或上方?
实现黑色矩形尺寸坐标标注的完整方案
步骤1:提取并保存矩形数据
先调整你已有的提取命令,把矩形的尺寸坐标数据保存到临时文件,方便后续批量处理:
convert input.png -fill black +opaque '#FFFFFF' \ -define connected-components:verbose=true \ -define connected-components:area-threshold=5000 \ -define connected-components:mean-color=true \ -connected-components 4 /dev/null | awk '/srgb\(0,0,0\)/{print $2}' > rects.txt
如果需要保留二值化处理后的图像,把/dev/null换回output.png即可。
步骤2:批量添加文本标注
编写脚本读取rects.txt中的每一行数据,拆分出矩形的宽度(W)、高度(H)、左上角X/Y坐标,计算文本的绘制位置后,用ImageMagick叠加标注:
# 复制原始图像作为标注的基础图 cp input.png labeled_output.png # 循环处理每个矩形的标注 while read rect; do # 拆分WxH+X+Y格式的字符串 W=$(echo "$rect" | cut -d'x' -f1) H=$(echo "$rect" | cut -d'x' -f2 | cut -d'+' -f1) X=$(echo "$rect" | cut -d'+' -f2) Y=$(echo "$rect" | cut -d'+' -f3) # 方案1:标注在矩形顶部居中(向上偏移10像素避免贴边) text_x=$((X + W/2)) text_y=$((Y - 10)) # 方案2:标注在矩形内部居中(取消注释即可切换) # text_x=$((X + W/2)) # text_y=$((Y + H/2)) # 叠加文本标注,可根据需求调整字体、大小、颜色 convert labeled_output.png \ -font Arial -pointsize 16 -fill white \ -gravity center -draw "text $text_x,$text_y '$rect'" \ labeled_output.png done < rects.txt
关键参数说明
-font:指定标注字体,可根据系统可用字体调整(如Helvetica、Noto Sans)-pointsize:设置文本大小,可根据矩形尺寸灵活调整-fill:文本颜色,白色在黑色矩形上对比度最高,也可替换为其他醒目颜色-gravity center:让文本以计算出的坐标为中心绘制,确保对齐效果
无临时文件的整合版本
如果不想生成临时文件,可直接通过管道传递数据完成提取+标注:
convert input.png -fill black +opaque '#FFFFFF' \ -define connected-components:verbose=true \ -define connected-components:area-threshold=5000 \ -define connected-components:mean-color=true \ -connected-components 4 /dev/null | awk '/srgb\(0,0,0\)/{print $2}' | \ while read rect; do W=$(echo "$rect" | cut -d'x' -f1) H=$(echo "$rect" | cut -d'x' -f2 | cut -d'+' -f1) X=$(echo "$rect" | cut -d'+' -f2) Y=$(echo "$rect" | cut -d'+' -f3) text_x=$((X + W/2)) text_y=$((Y - 10)) # 第一次循环先复制基础图,后续循环直接叠加 if [ ! -f labeled_output.png ]; then cp input.png labeled_output.png fi convert labeled_output.png \ -font Arial -pointsize 16 -fill white \ -gravity center -draw "text $text_x,$text_y '$rect'" \ labeled_output.png done
注意:若使用ImageMagick 7版本,需将命令中的
convert替换为magick。
内容的提问来源于stack exchange,提问作者Rasec Malkic
相关产品推荐
相关产品推荐

