~whereswaldon/trideo

trideo/main.go -rw-r--r-- 9.5 KiB
a885028bChris Waldon deps: update to latest gio 5 months ago
                                                                                
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
package main

import (
	"bufio"
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"image"
	"image/color"
	_ "image/jpeg"
	"log"
	"os"
	"time"

	"git.sr.ht/~whereswaldon/latest"
	//	"golang.org/x/image/draw"

	"gioui.org/app"
	"gioui.org/f32"
	"gioui.org/io/key"
	"gioui.org/io/system"
	"gioui.org/layout"
	"gioui.org/op"
	"gioui.org/op/clip"
	"gioui.org/op/paint"
	"gioui.org/unit"
	"gioui.org/widget"
	"github.com/blackjack/webcam"
	"github.com/esimov/triangle"
	"github.com/pkg/profile"
)

func main() {
	var useProfiling bool
	flag.BoolVar(&useProfiling, "profile", false, "enable pprof profiling")
	go func() {
		w := app.NewWindow(app.Title("Trideo"))
		if err := loop(w, useProfiling); err != nil {
			log.Fatal(err)
		}
		os.Exit(0)
	}()
	app.Main()
}

// dump prints a JSONified struct to stdout.
func dump(in interface{}) {
	b, _ := json.MarshalIndent(in, "", "  ")
	fmt.Println(string(b))
}

// Timings holds performance timing information from throughout the render
// process.
type Timings struct {
	Start, Capture, Decode, Convert, Blur, Gray, Sobel, Point, Delaunay time.Time
}

func (t Timings) String() string {
	return fmt.Sprintln("tot:", t.Delaunay.Sub(t.Start))
}

// Result contains the result of rendering a single frame of video
type Result struct {
	// Triangles holds the list of Delaunay triangles representing the frame.
	Triangles []triangle.Triangle
	// Frame is the source image data.
	Frame *image.NRGBA
	// Timings is the performance information from generating this frame.
	Timings
	// Valid indicates whether or not this Result's data can be used. This will
	// be false if something interrupted the render process.
	Valid bool
}

// DebugResult holds all of the intermediate render data.
type DebugResult struct {
	Raw       *image.NRGBA
	Blur      *image.NRGBA
	Sobel     *image.NRGBA
	Points    []triangle.Point
	Triangles []triangle.Triangle
}

// FrameConfig holds the parameters provided to the renderer.
type FrameConfig struct {
	Debug bool
}

// MJPEGFourCC is the 4-byte code corresponding to the MJPEG codec in
// Video4Linux.
const MJPEGFourCC = 1196444237

// loops runs the webcam output UI.
func loop(w *app.Window, useProfiling bool) error {
	logOut := bufio.NewWriter(log.Writer())
	log.SetOutput(logOut)
	defer logOut.Flush()
	if useProfiling {
		defer profile.Start().Stop()
	}
	cam, err := webcam.Open("/dev/video0")
	if err != nil {
		panic(err)
	}
	defer cam.Close()
	if _, supported := cam.GetSupportedFormats()[MJPEGFourCC]; !supported {
		panic(fmt.Errorf("webcam doesn't support MJPEG"))
	}
	sizes := cam.GetSupportedFrameSizes(MJPEGFourCC)
	target := 0
	for index, config := range sizes {
		if config.MinWidth < sizes[target].MinWidth {
			target = index
		}
	}
	dump(sizes[target])
	format, width, height, err := cam.SetImageFormat(MJPEGFourCC, sizes[target].MaxWidth, sizes[target].MinHeight)
	if err != nil {
		panic(err)
	}
	log.Println("webcam confirms", format, width, height)
	if err := cam.SetBufferCount(1); err != nil {
		panic(err)
	}

	if err := cam.StartStreaming(); err != nil {
		panic(err)
	}

	p := triangle.Processor{
		BlurRadius:      4,
		SobelThreshold:  10,
		PointsThreshold: 20,
		MaxPoints:       500,
		StrokeWidth:     0,
		Wireframe:       0,
	}

	var ops op.Ops
	tickerDuration := time.Second / 10
	ticker := time.NewTicker(tickerDuration)
	var init bool
	var d triangle.Delaunay
	var tris Result
	worker := latest.NewWorker(func(in interface{}) interface{} {
		config := in.(FrameConfig)
		var timings Timings
		timings.Start = time.Now()
		if err := cam.WaitForFrame(1); err != nil {
			return tris
		}
		buf, err := cam.ReadFrame()
		if err != nil {
			return tris
		}
		timings.Capture = time.Now()
		frame, _, err := image.Decode(bytes.NewBuffer(buf))
		if err != nil {
			return tris
		}
		timings.Decode = time.Now()
		width, height := frame.Bounds().Dx(), frame.Bounds().Dy()
		asRGBA := triangle.ToNRGBA(frame)
		timings.Convert = time.Now()
		blur := asRGBA
		if p.BlurRadius > 0 {
			blur = triangle.StackBlur(asRGBA, uint32(p.BlurRadius))
		}
		timings.Blur = time.Now()
		sobel := triangle.SobelFilter(blur, float64(p.SobelThreshold))
		timings.Sobel = time.Now()
		points := triangle.GetEdgePoints(sobel, p.PointsThreshold, p.MaxPoints)
		timings.Point = time.Now()

		triangles := d.Init(width, height).Insert(points).GetTriangles()
		timings.Delaunay = time.Now()
		if config.Debug {
			go DebugWindow(DebugResult{
				Raw:       asRGBA,
				Blur:      blur,
				Sobel:     sobel,
				Points:    points,
				Triangles: triangles,
			})
		}
		return Result{Triangles: triangles, Frame: asRGBA, Timings: timings, Valid: true}

	})
	var aspect float32
	var debug bool
	for {
		select {
		case img := <-worker.Raw():
			tris = img.(Result)
			if tris.Valid {
				if !init {
					aspect = float32(tris.Frame.Bounds().Dx()) / float32(tris.Frame.Bounds().Dy())
				}
				init = true
				w.Invalidate()
			}
		case <-ticker.C:
			worker.Push(FrameConfig{Debug: debug})
			debug = false
		case e := <-w.Events():
			switch e := e.(type) {
			case system.DestroyEvent:
				return e.Err
			case system.FrameEvent:
				start := time.Now()
				sz := layout.FPt(e.Size)
				szAspect := sz.X / sz.Y
				if init && (szAspect-aspect > 0.01 || szAspect-aspect < -0.01) {
					width, height := unit.Dp(sz.Y*aspect), unit.Dp(sz.Y)
					log.Println(aspect, szAspect, width, height)
					w.Option(app.Size(width, height))
					w.Invalidate()
				}
				gtx := layout.NewContext(&ops, e)
				if init {
					paint.Fill(gtx.Ops, color.NRGBA{A: 255})
					op.Affine(f32.Affine2D{}.Scale(f32.Point{}, f32.Point{
						X: float32(gtx.Constraints.Max.X) / float32(tris.Frame.Rect.Dx()),
						Y: float32(gtx.Constraints.Max.Y) / float32(tris.Frame.Rect.Dy()),
					})).Add(gtx.Ops)
					for _, t := range tris.Triangles {
						LayoutDelaunyTriangle(gtx, t, tris.Frame)
					}
				}
				e.Frame(gtx.Ops)
				now := time.Now()
				log.Println("frame", now.Sub(start), "latency", now.Sub(tris.Start))
			case key.Event:
				if e.Name == key.NameSpace {
					debug = true
				}
			}
		}
	}
}

// Dp converts an integer quantity into unit.Dp.
func Dp(in int) unit.Value {
	return unit.Dp(float32(in))
}

// DebugWindow launches a new Gio window to present the DebugResult for
// visual inspection.
func DebugWindow(result DebugResult) {
	width := result.Raw.Rect.Dx() * 4
	height := result.Raw.Rect.Dy() * 8
	w := app.NewWindow(app.Title("Debug"), app.MinSize(Dp(width), Dp(height)))
	var ops op.Ops
	var list layout.List
	list.Axis = layout.Vertical
	for {
		select {
		case e := <-w.Events():
			switch e := e.(type) {
			case system.DestroyEvent:
				return
			case system.FrameEvent:
				gtx := layout.NewContext(&ops, e)
				list.Layout(gtx, 5, func(gtx layout.Context, index int) layout.Dimensions {
					switch index {
					case 0:
						return LayoutImage(gtx, result.Raw)
					case 1:
						return LayoutImage(gtx, result.Blur)
					case 2:
						return LayoutImage(gtx, result.Sobel)
					case 3:
						return LayoutPointsOnImage(gtx, result.Sobel, result.Points)
					case 4:
						return LayoutTrianglesOnImage(gtx, result.Sobel, result.Triangles)
					default:
						return layout.Dimensions{}
					}
				})
				e.Frame(gtx.Ops)
			}

		}
	}
}

// LayoutPointsOnImage lays out an image with some points superimposed on
// top of it.
func LayoutPointsOnImage(gtx layout.Context, img image.Image, points []triangle.Point) layout.Dimensions {
	dims := LayoutImage(gtx, img)
	scale := float32(dims.Size.X) / float32(img.Bounds().Dx())
	defer op.Save(gtx.Ops).Load()
	op.Affine(f32.Affine2D{}.Scale(f32.Point{}, f32.Point{X: scale, Y: scale})).Add(gtx.Ops)
	for _, p := range points {
		pt := f32.Point{X: float32(p.X), Y: float32(p.Y)}
		DrawPoint(gtx, pt)
	}
	return dims
}

// DrawPoint renders a small green point at the provided location.
func DrawPoint(gtx layout.Context, p f32.Point) {
	paint.FillShape(gtx.Ops, color.NRGBA{G: 255, A: 255},
		clip.Circle{
			Center: p,
			Radius: 0.3,
		}.Op(gtx.Ops))
}

// LayoutTrianglesOnImage renders a image with triangles and their center
// points indicated on top of it.
func LayoutTrianglesOnImage(gtx layout.Context, img image.Image, tris []triangle.Triangle) layout.Dimensions {
	dims := LayoutImage(gtx, img)
	scale := float32(dims.Size.X) / float32(img.Bounds().Dx())
	defer op.Save(gtx.Ops).Load()
	op.Affine(f32.Affine2D{}.Scale(f32.Point{}, f32.Point{X: scale, Y: scale})).Add(gtx.Ops)
	for _, t := range tris {
		path, center := TriPath(gtx, t)
		outline := clip.Stroke{
			Path: path,
			Style: clip.StrokeStyle{
				Width: 0.1,
			},
		}.Op()
		paint.FillShape(gtx.Ops, color.NRGBA{G: 255, A: 255}, outline)
		DrawPoint(gtx, layout.FPt(center))
	}
	return dims
}

// LayoutImage displays an image contained by the gtx constraints.
func LayoutImage(gtx layout.Context, img image.Image) layout.Dimensions {
	imgOp := paint.NewImageOp(img)
	return widget.Image{
		Src: imgOp,
		Fit: widget.Contain,
	}.Layout(gtx)
}

// TriPath returns the path representing the given triangle as well as the
// triangle's center point.
func TriPath(gtx layout.Context, t triangle.Triangle) (clip.PathSpec, image.Point) {
	p := clip.Path{}
	p.Begin(gtx.Ops)
	a, b, c := t.Nodes[0], t.Nodes[1], t.Nodes[2]
	cx := (a.X + b.X + c.X) / 3
	cy := (a.Y + b.Y + c.Y) / 3
	p.MoveTo(layout.FPt(image.Pt(a.X, a.Y)))
	p.LineTo(layout.FPt(image.Pt(b.X, b.Y)))
	p.LineTo(layout.FPt(image.Pt(c.X, c.Y)))
	p.Close()
	return p.End(), image.Pt(cx, cy)
}

// LayoutDelaunyTriangle renders a single colored triangle.
func LayoutDelaunyTriangle(gtx layout.Context, t triangle.Triangle, frame *image.NRGBA) {
	path, center := TriPath(gtx, t)
	outline := clip.Outline{Path: path}.Op()
	paint.FillShape(gtx.Ops, frame.At(center.X, center.Y).(color.NRGBA), outline)
}