Debian Codegraph @

convolution.go

raw symbols SCIP
1 package gift
2
3 import (
4 "image"
5 "image/draw"
6 "math"
7 )
8
9 type uweight struct {
10 u int
11 weight float32
12 }
13
14 type uvweight struct {
15 u int
16 v int
17 weight float32
18 }
19
20 func prepareConvolutionWeights(kernel []float32, normalize bool) (int, []uvweight) {
21 size := int(math.Sqrt(float64(len(kernel))))
22 if size%2 == 0 {
23 size--
24 }
25 if size < 1 {
26 return 0, []uvweight{}
27 }
28 center := size / 2
29
30 weights := []uvweight{}
31 for i := 0; i < size; i++ {
32 for j := 0; j < size; j++ {
33 k := j*size + i
34 w := float32(0)
35 if k < len(kernel) {
36 w = kernel[k]
37 }
38 if w != 0 {
39 weights = append(weights, uvweight{u: i - center, v: j - center, weight: w})
40 }
41 }
42 }
43
44 if !normalize {
45 return size, weights
46 }
47
48 var sum, sumpositive float32
49 for _, w := range weights {
50 sum += w.weight
51 if w.weight > 0 {
52 sumpositive += w.weight
53 }
54 }
55
56 var div float32
57 if sum != 0 {
58 div = sum
59 } else if sumpositive != 0 {
60 div = sumpositive
61 } else {
62 return size, weights
63 }
64
65 for i := 0; i < len(weights); i++ {
66 weights[i].weight /= div
67 }
68
69 return size, weights
70 }
71
72 type convolutionFilter struct {
73 kernel []float32
74 normalize bool
75 alpha bool
76 abs bool
77 delta float32
78 }
79
80 func (p *convolutionFilter) Bounds(srcBounds image.Rectangle) (dstBounds image.Rectangle) {
81 dstBounds = image.Rect(0, 0, srcBounds.Dx(), srcBounds.Dy())
82 return
83 }
84
85 func (p *convolutionFilter) Draw(dst draw.Image, src image.Image, options *Options) {
86 if options == nil {
87 options = &defaultOptions
88 }
89
90 srcb := src.Bounds()
91 dstb := dst.Bounds()
92
93 if srcb.Dx() <= 0 || srcb.Dy() <= 0 {
94 return
95 }
96
97 ksize, weights := prepareConvolutionWeights(p.kernel, p.normalize)
98 kcenter := ksize / 2
99
100 if ksize < 1 {
101 copyimage(dst, src, options)
102 return
103 }
104
105 pixGetter := newPixelGetter(src)
106 pixSetter := newPixelSetter(dst)
107
108 parallelize(options.Workers, srcb.Min.Y, srcb.Max.Y, func(start, stop int) {
109 // Init temporary rows.
110 starty := start
111 rows := make([][]pixel, ksize)
112 for i := range ksize {
113 rowy := starty + i - kcenter
114 if rowy < srcb.Min.Y {
115 rowy = srcb.Min.Y
116 } else if rowy > srcb.Max.Y-1 {
117 rowy = srcb.Max.Y - 1
118 }
119 row := make([]pixel, srcb.Dx())
120 pixGetter.getPixelRow(rowy, &row)
121 rows[i] = row
122 }
123
124 for y := start; y < stop; y++ {
125 // Calculate dst row.
126 for x := srcb.Min.X; x < srcb.Max.X; x++ {
127 var r, g, b, a float32
128 for _, w := range weights {
129 wx := x + w.u
130 if wx < srcb.Min.X {
131 wx = srcb.Min.X
132 } else if wx > srcb.Max.X-1 {
133 wx = srcb.Max.X - 1
134 }
135 rowsx := wx - srcb.Min.X
136 rowsy := kcenter + w.v
137
138 px := rows[rowsy][rowsx]
139 r += px.r * w.weight
140 g += px.g * w.weight
141 b += px.b * w.weight
142 if p.alpha {
143 a += px.a * w.weight
144 }
145 }
146 if p.abs {
147 r = absf32(r)
148 g = absf32(g)
149 b = absf32(b)
150 if p.alpha {
151 a = absf32(a)
152 }
153 }
154 if p.delta != 0 {
155 r += p.delta
156 g += p.delta
157 b += p.delta
158 if p.alpha {
159 a += p.delta
160 }
161 }
162 if !p.alpha {
163 a = rows[kcenter][x-srcb.Min.X].a
164 }
165 pixSetter.setPixel(dstb.Min.X+x-srcb.Min.X, dstb.Min.Y+y-srcb.Min.Y, pixel{r, g, b, a})
166 }
167
168 // Rotate temporary rows.
169 if y < stop-1 {
170 tmprow := rows[0]
171 for i := 0; i < ksize-1; i++ {
172 rows[i] = rows[i+1]
173 }
174 nextrowy := min(y+ksize/2+1, srcb.Max.Y-1)
175 pixGetter.getPixelRow(nextrowy, &tmprow)
176 rows[ksize-1] = tmprow
177 }
178 }
179 })
180 }
181
182 // Convolution creates a filter that applies a square convolution kernel to an image.
183 // The length of the kernel slice must be the square of an odd kernel size (e.g. 9 for 3x3 kernel, 25 for 5x5 kernel).
184 // Excessive slice members will be ignored.
185 // If normalize parameter is true, the kernel will be normalized before applying the filter.
186 // If alpha parameter is true, the alpha component of color will be filtered too.
187 // If abs parameter is true, absolute values of color components will be taken after doing calculations.
188 // If delta parameter is not zero, this value will be added to the filtered pixels.
189 //
190 // Example:
191 //
192 // // Apply the emboss filter to an image.
193 // g := gift.New(
194 // gift.Convolution(
195 // []float32{
196 // -1, -1, 0,
197 // -1, 1, 1,
198 // 0, 1, 1,
199 // },
200 // false, false, false, 0,
201 // ),
202 // )
203 // dst := image.NewRGBA(g.Bounds(src.Bounds()))
204 // g.Draw(dst, src)
205 func Convolution(kernel []float32, normalize, alpha, abs bool, delta float32) Filter {
206 return &convolutionFilter{
207 kernel: kernel,
208 normalize: normalize,
209 alpha: alpha,
210 abs: abs,
211 delta: delta,
212 }
213 }
214
215 // prepareConvolutionWeights1d prepares pixel weights using a convolution kernel.
216 // Weights equal to 0 are excluded.
217 func prepareConvolutionWeights1d(kernel []float32) (int, []uweight) {
218 size := len(kernel)
219 if size%2 == 0 {
220 size--
221 }
222 if size < 1 {
223 return 0, []uweight{}
224 }
225 center := size / 2
226 weights := []uweight{}
227 for i := 0; i < size; i++ {
228 w := float32(0)
229 if i < len(kernel) {
230 w = kernel[i]
231 }
232 if w != 0 {
233 weights = append(weights, uweight{i - center, w})
234 }
235 }
236 return size, weights
237 }
238
239 // convolveLine convolves a single line of pixels according to the given weights.
240 func convolveLine(dstBuf []pixel, srcBuf []pixel, weights []uweight) {
241 max := len(srcBuf) - 1
242 if max < 0 {
243 return
244 }
245 for dstu := range srcBuf {
246 var r, g, b, a float32
247 for _, w := range weights {
248 k := dstu + w.u
249 if k < 0 {
250 k = 0
251 } else if k > max {
252 k = max
253 }
254 c := srcBuf[k]
255 wa := c.a * w.weight
256 r += c.r * wa
257 g += c.g * wa
258 b += c.b * wa
259 a += wa
260 }
261 if a != 0 {
262 r /= a
263 g /= a
264 b /= a
265 }
266 dstBuf[dstu] = pixel{r, g, b, a}
267 }
268 }
269
270 // convolve1dv performs a fast vertical 1d convolution.
271 func convolve1dv(dst draw.Image, src image.Image, kernel []float32, options *Options) {
272 srcb := src.Bounds()
273 dstb := dst.Bounds()
274 if srcb.Dx() <= 0 || srcb.Dy() <= 0 {
275 return
276 }
277 if len(kernel) < 1 {
278 copyimage(dst, src, options)
279 return
280 }
281 _, weights := prepareConvolutionWeights1d(kernel)
282 pixGetter := newPixelGetter(src)
283 pixSetter := newPixelSetter(dst)
284 parallelize(options.Workers, srcb.Min.X, srcb.Max.X, func(start, stop int) {
285 buf := getPixelBuf(srcb.Dy(), srcb.Dy())
286 defer putPixelBuf(buf)
287
288 for x := start; x < stop; x++ {
289 pixGetter.getPixelColumn(x, &buf.src)
290 convolveLine(buf.dst, buf.src, weights)
291 pixSetter.setPixelColumn(dstb.Min.X+x-srcb.Min.X, buf.dst)
292 }
293 })
294 }
295
296 // convolve1dh performs afast horizontal 1d convolution.
297 func convolve1dh(dst draw.Image, src image.Image, kernel []float32, options *Options) {
298 srcb := src.Bounds()
299 dstb := dst.Bounds()
300 if srcb.Dx() <= 0 || srcb.Dy() <= 0 {
301 return
302 }
303 if len(kernel) < 1 {
304 copyimage(dst, src, options)
305 return
306 }
307 _, weights := prepareConvolutionWeights1d(kernel)
308 pixGetter := newPixelGetter(src)
309 pixSetter := newPixelSetter(dst)
310 parallelize(options.Workers, srcb.Min.Y, srcb.Max.Y, func(start, stop int) {
311 buf := getPixelBuf(srcb.Dx(), srcb.Dx())
312 defer putPixelBuf(buf)
313
314 for y := start; y < stop; y++ {
315 pixGetter.getPixelRow(y, &buf.src)
316 convolveLine(buf.dst, buf.src, weights)
317 pixSetter.setPixelRow(dstb.Min.Y+y-srcb.Min.Y, buf.dst)
318 }
319 })
320 }
321
322 func gaussianBlurKernel(x, sigma float32) float32 {
323 return float32(math.Exp(-float64(x*x)/float64(2*sigma*sigma)) / (float64(sigma) * math.Sqrt(2*math.Pi)))
324 }
325
326 type gausssianBlurFilter struct {
327 sigma float32
328 }
329
330 func (p *gausssianBlurFilter) Bounds(srcBounds image.Rectangle) (dstBounds image.Rectangle) {
331 dstBounds = image.Rect(0, 0, srcBounds.Dx(), srcBounds.Dy())
332 return
333 }
334
335 func (p *gausssianBlurFilter) Draw(dst draw.Image, src image.Image, options *Options) {
336 if options == nil {
337 options = &defaultOptions
338 }
339
340 srcb := src.Bounds()
341 if srcb.Dx() <= 0 || srcb.Dy() <= 0 {
342 return
343 }
344
345 if p.sigma <= 0 {
346 copyimage(dst, src, options)
347 return
348 }
349
350 radius := int(math.Ceil(float64(p.sigma * 3)))
351 size := 2*radius + 1
352 center := radius
353 kernel := make([]float32, size)
354
355 kernel[center] = gaussianBlurKernel(0, p.sigma)
356 sum := kernel[center]
357
358 for i := 1; i <= radius; i++ {
359 f := gaussianBlurKernel(float32(i), p.sigma)
360 kernel[center-i] = f
361 kernel[center+i] = f
362 sum += 2 * f
363 }
364
365 for i := range kernel {
366 kernel[i] /= sum
367 }
368
369 tmp := createTempImage(srcb)
370 convolve1dh(tmp, src, kernel, options)
371 convolve1dv(dst, tmp, kernel, options)
372 }
373
374 // GaussianBlur creates a filter that applies a gaussian blur to an image.
375 // The sigma parameter must be positive and indicates how much the image will be blurred.
376 // Blur affected radius roughly equals 3 * sigma.
377 //
378 // Example:
379 //
380 // g := gift.New(
381 // gift.GaussianBlur(1.5),
382 // )
383 // dst := image.NewRGBA(g.Bounds(src.Bounds()))
384 // g.Draw(dst, src)
385 func GaussianBlur(sigma float32) Filter {
386 return &gausssianBlurFilter{
387 sigma: sigma,
388 }
389 }
390
391 type unsharpMaskFilter struct {
392 sigma float32
393 amount float32
394 threshold float32
395 }
396
397 func (p *unsharpMaskFilter) Bounds(srcBounds image.Rectangle) (dstBounds image.Rectangle) {
398 dstBounds = image.Rect(0, 0, srcBounds.Dx(), srcBounds.Dy())
399 return
400 }
401
402 func unsharp(orig, blurred, amount, threshold float32) float32 {
403 dif := (orig - blurred) * amount
404 if absf32(dif) > absf32(threshold) {
405 return orig + dif
406 }
407 return orig
408 }
409
410 func (p *unsharpMaskFilter) Draw(dst draw.Image, src image.Image, options *Options) {
411 if options == nil {
412 options = &defaultOptions
413 }
414
415 srcb := src.Bounds()
416 dstb := dst.Bounds()
417
418 if srcb.Dx() <= 0 || srcb.Dy() <= 0 {
419 return
420 }
421
422 blurred := createTempImage(srcb)
423 blur := GaussianBlur(p.sigma)
424 blur.Draw(blurred, src, options)
425
426 pixGetterOrig := newPixelGetter(src)
427 pixGetterBlur := newPixelGetter(blurred)
428 pixelSetter := newPixelSetter(dst)
429
430 parallelize(options.Workers, srcb.Min.Y, srcb.Max.Y, func(start, stop int) {
431 for y := start; y < stop; y++ {
432 for x := srcb.Min.X; x < srcb.Max.X; x++ {
433 pxOrig := pixGetterOrig.getPixel(x, y)
434 pxBlur := pixGetterBlur.getPixel(x, y)
435
436 r := unsharp(pxOrig.r, pxBlur.r, p.amount, p.threshold)
437 g := unsharp(pxOrig.g, pxBlur.g, p.amount, p.threshold)
438 b := unsharp(pxOrig.b, pxBlur.b, p.amount, p.threshold)
439 a := unsharp(pxOrig.a, pxBlur.a, p.amount, p.threshold)
440
441 pixelSetter.setPixel(dstb.Min.X+x-srcb.Min.X, dstb.Min.Y+y-srcb.Min.Y, pixel{r, g, b, a})
442 }
443 }
444 })
445 }
446
447 // UnsharpMask creates a filter that sharpens an image.
448 // The sigma parameter is used in a gaussian function and affects the radius of effect.
449 // Sigma must be positive. Sharpen radius roughly equals 3 * sigma.
450 // The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5.
451 // The threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05.
452 //
453 // Example:
454 //
455 // g := gift.New(
456 // gift.UnsharpMask(1, 1, 0),
457 // )
458 // dst := image.NewRGBA(g.Bounds(src.Bounds()))
459 // g.Draw(dst, src)
460 func UnsharpMask(sigma, amount, threshold float32) Filter {
461 return &unsharpMaskFilter{
462 sigma: sigma,
463 amount: amount,
464 threshold: threshold,
465 }
466 }
467
468 type meanFilter struct {
469 ksize int
470 disk bool
471 }
472
473 func (p *meanFilter) Bounds(srcBounds image.Rectangle) (dstBounds image.Rectangle) {
474 dstBounds = image.Rect(0, 0, srcBounds.Dx(), srcBounds.Dy())
475 return
476 }
477
478 func (p *meanFilter) Draw(dst draw.Image, src image.Image, options *Options) {
479 if options == nil {
480 options = &defaultOptions
481 }
482
483 srcb := src.Bounds()
484 if srcb.Dx() <= 0 || srcb.Dy() <= 0 {
485 return
486 }
487
488 ksize := p.ksize
489 if ksize%2 == 0 {
490 ksize--
491 }
492
493 if ksize <= 1 {
494 copyimage(dst, src, options)
495 return
496 }
497
498 if p.disk {
499 diskKernel := genDisk(p.ksize)
500 f := Convolution(diskKernel, true, true, false, 0)
501 f.Draw(dst, src, options)
502 } else {
503 kernel := make([]float32, ksize*ksize)
504 for i := range kernel {
505 kernel[i] = 1
506 }
507 f := Convolution(kernel, true, true, false, 0)
508 f.Draw(dst, src, options)
509 }
510 }
511
512 // Mean creates a local mean image filter.
513 // Takes an average across a neighborhood for each pixel.
514 // The ksize parameter is the kernel size. It must be an odd positive integer (for example: 3, 5, 7).
515 // If the disk parameter is true, a disk-shaped neighborhood will be used instead of a square neighborhood.
516 func Mean(ksize int, disk bool) Filter {
517 return &meanFilter{
518 ksize: ksize,
519 disk: disk,
520 }
521 }
522
523 type hvConvolutionFilter struct {
524 hkernel, vkernel []float32
525 }
526
527 func (p *hvConvolutionFilter) Bounds(srcBounds image.Rectangle) (dstBounds image.Rectangle) {
528 dstBounds = image.Rect(0, 0, srcBounds.Dx(), srcBounds.Dy())
529 return
530 }
531
532 func (p *hvConvolutionFilter) Draw(dst draw.Image, src image.Image, options *Options) {
533 if options == nil {
534 options = &defaultOptions
535 }
536
537 srcb := src.Bounds()
538 dstb := dst.Bounds()
539
540 if srcb.Dx() <= 0 || srcb.Dy() <= 0 {
541 return
542 }
543
544 tmph := createTempImage(srcb)
545 Convolution(p.hkernel, false, false, true, 0).Draw(tmph, src, options)
546 pixGetterH := newPixelGetter(tmph)
547
548 tmpv := createTempImage(srcb)
549 Convolution(p.vkernel, false, false, true, 0).Draw(tmpv, src, options)
550 pixGetterV := newPixelGetter(tmpv)
551
552 pixSetter := newPixelSetter(dst)
553
554 parallelize(options.Workers, srcb.Min.Y, srcb.Max.Y, func(start, stop int) {
555 for y := start; y < stop; y++ {
556 for x := srcb.Min.X; x < srcb.Max.X; x++ {
557 pxh := pixGetterH.getPixel(x, y)
558 pxv := pixGetterV.getPixel(x, y)
559 r := sqrtf32(pxh.r*pxh.r + pxv.r*pxv.r)
560 g := sqrtf32(pxh.g*pxh.g + pxv.g*pxv.g)
561 b := sqrtf32(pxh.b*pxh.b + pxv.b*pxv.b)
562 pixSetter.setPixel(dstb.Min.X+x-srcb.Min.X, dstb.Min.Y+y-srcb.Min.Y, pixel{r, g, b, pxh.a})
563 }
564 }
565 })
566 }
567
568 // Sobel creates a filter that applies a sobel operator to an image.
569 func Sobel() Filter {
570 return &hvConvolutionFilter{
571 hkernel: []float32{-1, 0, 1, -2, 0, 2, -1, 0, 1},
572 vkernel: []float32{-1, -2, -1, 0, 0, 0, 1, 2, 1},
573 }
574 }