Golang在图像中绘制矩形框的示例代码
更新时间:2024年04月02日 09:52:02 作者: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绘制矩形框内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
gorm 结构体中 binding 和 msg 结构体标签示例详解
文章介绍了Gin框架中binding和msg结构体标签的使用,包括基本用法、常用验证规则、自定义验证器、错误信息自定义、控制器使用示例、组合验证规则、跨字段验证和初始化验证器等,这些标签主要用于数据验证、自定义错误信息、参数绑定和表单验证2024-11-11
Golang实现RabbitMQ中死信队列几种情况
本文主要介绍了Golang实现RabbitMQ中死信队列几种情况,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2023-03-03


最新评论