-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
100 lines (84 loc) · 2.13 KB
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package yolotriton
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/jpeg"
_ "image/png"
"os"
"github.com/golang/freetype/truetype"
"golang.org/x/image/font"
"golang.org/x/image/font/gofont/goregular"
"golang.org/x/image/math/fixed"
)
func LoadImage(imagePath string) (image.Image, error) {
file, err := os.Open(imagePath)
if err != nil {
return nil, err
}
defer file.Close()
img, _, err := image.Decode(file)
if err != nil {
return nil, err
}
return img, nil
}
func SaveImage(img image.Image, filename string) error {
file, err := os.Create(filename)
if err != nil {
return err
}
defer file.Close()
err = jpeg.Encode(file, img, nil)
if err != nil {
return err
}
return nil
}
func DrawBoundingBoxes(img image.Image, boxes []Box, lineWidth int, fontSize float64) (image.Image, error) {
// Create a new RGBA image to draw the bounding boxes and text labels on
bounds := img.Bounds()
dst := image.NewRGBA(bounds)
// Copy the original image to the destination image
draw.Draw(dst, bounds, img, bounds.Min, draw.Over)
// Create a color for the bounding boxes (red in this example)
red := color.RGBA{255, 0, 0, 255}
// Create a font from a TrueType font file with the specified font size
ttfFont, err := truetype.Parse(goregular.TTF)
if err != nil {
return nil, err
}
face := truetype.NewFace(ttfFont, &truetype.Options{
Size: fontSize,
})
// Draw the bounding boxes and text labels on the destination image
for _, box := range boxes {
x1, y1, x2, y2 := box.X1, box.Y1, box.X2, box.Y2
// Draw the bounding box
for x := x1; x <= x2; x++ {
for w := 0; w < lineWidth; w++ {
dst.Set(int(x), int(y1)+w, red)
dst.Set(int(x), int(y2)+w, red)
}
}
for y := y1; y <= y2; y++ {
for w := 0; w < lineWidth; w++ {
dst.Set(int(x1)+w, int(y), red)
dst.Set(int(x2)+w, int(y), red)
}
}
// Draw the text label above the box
label := fmt.Sprintf("%s %f", box.Class, box.Probability)
textX := int(x1)
textY := int(y1) - 5
d := &font.Drawer{
Dst: dst,
Src: image.NewUniform(red),
Face: face,
Dot: fixed.P(textX, textY),
}
d.DrawString(label)
}
return dst, nil
}