Golang在图像中绘制矩形框的示例代码
作者:Digital2Slave
这篇文章主要介绍了Golang在图像中绘制矩形框的示例代码,文中有详细的代码示例供大家参考,具有一定的参考价值,需要的朋友可以参考下
Golang 在图像中绘制矩形框
从获取的坐标信息,在图像中绘制矩形框,并添加标注信息。
1. 依赖
- 字体 simsun.ttc
- 第三方库 github.com/fogleman/gg
2. 源码
package main
import (
"encoding/json"
"fmt"
"image"
"image/color"
"image/draw"
"log"
"math"
"reflect"
"strings"
"github.com/fogleman/gg"
)
// test_draw_rect_text 画图像矩形, 标注, 颜色; 返回保存图像路径
// ref: https://github.com/fogleman/gg/blob/master/examples/rotated-image.go
func test_draw_rect_text(im_path, font_path, detect_label, save_path string, x, y, w, h float64) {
// Load image
im, err := gg.LoadImage(im_path)
if err != nil {
log.Fatal(err)
}
// 1 method
// iw, ih := im.Bounds().Dx(), im.Bounds().Dy()
// Set Context
// dc := gg.NewContext(iw, ih)
// Draw image
// dc.DrawImage(im, 0, 0)
// 2 method
dc := gg.NewContextForImage(im)
// Set color and line width
dc.SetHexColor("#FF0000")
dc.SetLineWidth(1)
// Draw rectangle
dc.DrawRoundedRectangle(x, y, w, h, 0)
// Store set
dc.Stroke()
// Set font and draw label
var font_height float64 = 7
if err := dc.LoadFontFace(font_path, font_height); err != nil {
panic(err)
}
rect_center_x := x + w/2
rect_center_y := y + h/2
dc.DrawStringAnchored(detect_label, rect_center_x, rect_center_y, 0.5, 0.5)
dc.Clip()
// Save png image
dc.SavePNG(save_path)
}
func main() {
im_path := "/home/tianzx/Pictures/lena.jpeg"
font_path := "/home/tianzx/ai_model/simsun.ttc"
detect_label := "缺角/碎裂"
save_path := "/home/tianzx/Pictures/lena_test.png"
var x, y, w, h float64 = 50, 100, 50, 50
test_draw_rect_text(im_path, font_path, detect_label, save_path, x, y, w, h)
}
3. 结果


4. 说明
导入的Golang第三方库,并不是都使用了,按需进行删减。
到此这篇关于Golang在图像中绘制矩形框的示例代码的文章就介绍到这了,更多相关Golang绘制矩形框内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
