Golang在圖像中繪制矩形框的示例代碼
更新時間:2024年04月02日 09:52:02 作者:Digital2Slave
這篇文章主要介紹了Golang在圖像中繪制矩形框的示例代碼,文中有詳細(xì)的代碼示例供大家參考,具有一定的參考價值,需要的朋友可以參考下
Golang 在圖像中繪制矩形框
從獲取的坐標(biāo)信息,在圖像中繪制矩形框,并添加標(biāo)注信息。
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 畫圖像矩形, 標(biāo)注, 顏色; 返回保存圖像路徑 // 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. 結(jié)果
4. 說明
導(dǎo)入的Golang第三方庫,并不是都使用了,按需進(jìn)行刪減。
到此這篇關(guān)于Golang在圖像中繪制矩形框的示例代碼的文章就介紹到這了,更多相關(guān)Golang繪制矩形框內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Go打印結(jié)構(gòu)體提升代碼調(diào)試效率實例詳解
這篇文章主要介紹了Go打印結(jié)構(gòu)體提升代碼調(diào)試效率實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-02-02淺析go中Ticker,Timer和Tick的用法與區(qū)別
在go面試的時候,面試官經(jīng)常會問time包的Ticker,Timer以及Tick的區(qū)別,一般在超時控制的時候用的比較多,今天就跟隨小編一起來詳細(xì)學(xué)一下這幾個的區(qū)別吧2023-10-10