-
Notifications
You must be signed in to change notification settings - Fork 1
/
bitmap.go
70 lines (57 loc) · 1.71 KB
/
bitmap.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
package astar
import (
"os"
"golang.org/x/image/bmp"
"image"
"image/color"
"image/draw"
"github.com/deckarep/golang-set"
)
func GraphFromBitmap(path string) (Graph, Node, Node) {
var start, end AStarNodeState
obstacles := mapset.NewSet()
bitmap := readBitmap(path + ".bmp")
bitmapSize := bitmap.Bounds().Size()
for x := 0; x < bitmapSize.X; x++ {
for y := 0; y < bitmapSize.Y; y++ {
pixel := bitmap.At(x, y)
if isStart(pixel) {
start = AStarNodeState{coordinates: Coordinates{x: x, y: y}, velocity: Velocity{x: 0, y: 0}}
}
if isEnd(pixel) {
end = AStarNodeState{coordinates: Coordinates{x: x, y: y}, velocity: Velocity{x: 0, y: 0}}
}
if isObstacle(pixel) {
obstacles.Add(Coordinates{x: x, y: y})
}
}
}
graph := MapOfSize(bitmapSize.X, bitmapSize.Y, obstacles)
return graph, graph.PointOf(start), graph.PointOf(end)
}
func PersistGraphToBitmap(path []Node, baseGraphPath string) {
bitmap := readBitmap(baseGraphPath + ".bmp").(draw.Image)
for _, aNode := range path {
astarNode := aNode.(AStarNode)
bitmap.Set(astarNode.state.coordinates.x, astarNode.state.coordinates.y, color.RGBA{R: 0, G: 0, B: 255, A: 255})
}
writeBitmap(bitmap, baseGraphPath + "_out.bmp")
}
func isStart(pixel color.Color) bool {
return pixel == color.RGBA{ R: 0, G: 255, B: 0, A: 255 }
}
func isEnd(pixel color.Color) bool {
return pixel == color.RGBA{ R: 255, G: 0, B: 0, A: 255 }
}
func isObstacle(pixel color.Color) bool {
return pixel == color.RGBA{ R: 0, G: 0, B: 0, A: 255 }
}
func readBitmap(path string) image.Image {
file, _ := os.Open(path)
bitmap, _ := bmp.Decode(file)
return bitmap
}
func writeBitmap(image image.Image, path string) {
res, _ := os.Create(path)
bmp.Encode(res, image)
}