-
Notifications
You must be signed in to change notification settings - Fork 0
/
commands.go
1449 lines (1370 loc) · 46 KB
/
commands.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
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 Fabian Wenzelmann
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gomosaic
import (
"bufio"
"errors"
"fmt"
"image"
"image/jpeg"
"image/png"
"io"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"time"
homedir "github.com/mitchellh/go-homedir"
"github.com/nfnt/resize"
)
var (
// ErrCmdSyntaxErr is returned by a CommandFunc if the syntax for the command
// is invalid.
ErrCmdSyntaxErr = errors.New("invalid command syntax")
)
type CmdVarietySelector int
const (
CmdVarietyNone CmdVarietySelector = iota
CmdVarietyRand
CmdVarietyMetric
)
func (s CmdVarietySelector) DisplayString() string {
switch s {
case CmdVarietyNone:
return "None"
case CmdVarietyRand:
return "Random"
case CmdVarietyMetric:
return "Metric"
default:
return "Unknown"
}
}
func ParseCMDVarietySelector(s string) (CmdVarietySelector, error) {
switch strings.ToLower(s) {
case "none":
return CmdVarietyNone, nil
case "random":
return CmdVarietyRand, nil
case "metric":
return CmdVarietyMetric, nil
default:
return -1, fmt.Errorf("unkown variety type: %s", s)
}
}
// TODO this state is rather specific for a file system version,
// maybe some more interfaces will help generalizing?
// But this is stuff for the future when more than images / histograms as
// files are supported
// ExecutorState is the state during a CommandHandler execution, see that
// type for more details of the workflow.
//
// The variables in the state are shared among the executions of the command
// functions.
type ExecutorState struct {
// WorkingDir is the current directory. It must always be an absolute path.
WorkingDir string
// Mapper is the current file system mapper.
Mapper *FSMapper
// ImgStorage is image database, backed by Mapper.
ImgStorage *FSImageDB
// NumRoutines is the number of go routines used for different tasks during
// mosaic generation.
NumRoutines int
// GCHStorage stores the global color histograms. Whenever new images are
// loaded the old histograms become invalid (set to nil again) and must
// be reloaded / created.
GCHStorage *MemoryHistStorage
// LCHStorage stores the local color histograms. Whenever new images are
// loaded the old histograms become invalid (set to nil again) and must
// be reloaded / created.
LCHStorage *MemoryLCHStorage
// Verbose is true if detailed output should be generated.
Verbose bool
// In is the source to read commands from (line by line).
In io.Reader
// Out is used to write state information.
Out io.Writer
// Option / config part
// CutMosaic describes whether the mosaic should be "cut".
// Cutting means to cut the resulting image s.t. each tile has the same bounds.
// Example: Suppose you want to divide an image with width 99 and want ten
// tiles horizontally. This leads to an image where each tile has
// a width of 9. Ten tiles yields to a final width of 90. As you see 9 pixels
// are "left over". The distribution in ten tiles is fixed, so we can't add
// another tile. But in order to enforce the original proposed width
// we can enlarge the last tile by 9 pixels. So we would have 9 tiles with
// width 9 and one tile with width 18.
//
// Cut controls what to do with those remaining pixels: If cut is set
// to true we skip the 9 pixels and return an image of size 90. If set to
// false we enlarge the last tile and return an image with size 99.
// Usually the default is false.
CutMosaic bool
// JPGQuality is the quality between 1 and 100 used when storing images.
// The higher the value the better the quality. We use a default quality of
// 100.
JPGQuality int
// InterP is the interpolation functions used when resizing the images.
InterP resize.InterpolationFunction
// Cache size is the size of the image cache during mosaic composition.
// The more elements in the cache the faster the composition process is, but
// it also increases memory consumption. If cache size is < 0 the
// DefaultCacheSize is used.
CacheSize int
// VarietySelector is the current variety selector, defaults to
// cmdVarietyNone.
VarietySelector CmdVarietySelector
// BestFit is the percent value (between 0 and 1) that describes how much
// percent of the input images are considered in the variety heaps.
BestFit float64
}
// GetPath returns the absolute path given some other path.
// The idea is the following: If the user inputs a path we have two cases:
// The user used an absolute path, in this case we use this absolute path
// to perform tasks with.
// If it is a relative path we join the working directory with this path
// and thus retrieve the absolute path we work on.
//
// The home directory can be used like on Unix: ~/Pictures is the Pictures
// directory in the home directory of the user.
func (state *ExecutorState) GetPath(path string) (string, error) {
var res string
// first extend with homedir
var pathErr error
res, pathErr = homedir.Expand(path)
if pathErr != nil {
return "", pathErr
}
// now we test if we have an absolute path or a relative path.
// if absolute path we don't need to do anything.
// if relative path we have to join with the base directory
if !filepath.IsAbs(res) {
// join with base dir
res = filepath.Join(state.WorkingDir, res)
}
// now convert to an absolute path again
res, pathErr = filepath.Abs(res)
if pathErr != nil {
return "", pathErr
}
return res, nil
}
// GetBestFitImages multiplies that best fit factor (BestFit) with num images
// to get the number of best fit images for the variety selectors. It sets
// same sane defaults in the case something weird happens.
func (state *ExecutorState) GetBestFitImages(numImages int) int {
asFloat := float64(numImages) * state.BestFit
asInt := int(asFloat)
return IntMin(IntMax(asInt, 1), numImages)
}
// CommandFunc is a function that is applied to the current states and
// arguments to that command.
type CommandFunc func(state *ExecutorState, args ...string) error
// Command a command consists of a function to actually execute the command
// and some information about the command.
type Command struct {
Exec CommandFunc
Usage string
Description string
}
// CommandMap maps command names to Commands.
type CommandMap map[string]Command
// DefaultCommands contains some commands that are often used.
var DefaultCommands CommandMap
// CommandHandler together with Execute implements a high-level command
// execution loop. CommandFuncs are applied to the current state until there
// are no more commands to execute (no more input).
//
// We won't go into the details, please read the source for details (yes,
// that's probably not the best practise but is so much easier in this case).
//
// A command has the form "COMMAND ARG1 ... ARGN" where COMMAND is the command
// name and ARG1 to ARGN are the arguments for the command.
//
// Here's a rough summary of what Execute will do:
// First it creates an initial state by calling Init. After that it immediately
// calls Start to notify the handler that the execution begins.
//
// We use to different methods to separate object creation from execution.
// Before a command is executed the Before method is called to notify the
// handler that a command will be executed.
//
// Then a loop will begin that reads all lines from the state's reader.
// If there is a command line the line will be parsed, if an error during
// parsing occurred the handler gets notified via OnParseErr. This method
// should return true if the execution should continue despite the error.
// Then a lookup in the provided command man happens: If the command was
// found the corresponding Command object is executed. If it was not found
// the OnInvalidCmd function is called on the handler. Again it should return
// true if the exeuction should continue despite the error. If this execution
// was successful the OnSuccess function is called with the executed command.
// If the execution was unsuccessful the OnError function will be called.
// Commands should return ErrCmdSyntaxErr if the syntax of the command is
// incorrect (for example invalid number of arguments) and OnError can do
// special handling in this case. Again OnError returns true if execution should
// continue.
// OnScanErr is called if there is an error while reading a command line from
// the state's reader.
//
// Errors while writing to the provided out stream might be reported, but
// this is not a requirement.
type CommandHandler interface {
Init() *ExecutorState
Start(s *ExecutorState)
Before(s *ExecutorState)
After(s *ExecutorState)
OnParseErr(s *ExecutorState, err error) bool
OnInvalidCmd(s *ExecutorState, cmd string) bool
OnSuccess(s *ExecutorState, cmd Command)
OnError(s *ExecutorState, err error, cmd Command) bool
OnScanErr(s *ExecutorState, err error)
}
// Execute implements the high-level execution loop as described in the
// documentation of CommandHandler. commandMap is used to lookup commands.
func Execute(handler CommandHandler, commandMap CommandMap) {
state := handler.Init()
handler.Start(state)
scanner := bufio.NewScanner(state.In)
for scanner.Scan() {
// a bit ugly with the calls to After:
// we want something like deferring in the loop...
handler.Before(state)
line := scanner.Text()
parsedCmd, parseErr := ParseCommand(line)
if parseErr != nil {
if !handler.OnParseErr(state, parseErr) {
return
}
handler.After(state)
continue
}
if len(parsedCmd) == 0 {
handler.After(state)
continue
}
cmd := parsedCmd[0]
if nextCmd, ok := commandMap[cmd]; ok {
// try to execute
if execErr := nextCmd.Exec(state, parsedCmd[1:]...); execErr == nil {
// execution of command was a success
handler.OnSuccess(state, nextCmd)
} else {
// execution of command failed
if !handler.OnError(state, execErr, nextCmd) {
return
}
// continue with next
handler.After(state)
continue
}
} else {
// we got an invalid command
if !handler.OnInvalidCmd(state, cmd) {
return
}
// continue with next command
handler.After(state)
continue
}
handler.After(state)
}
if scanErr := scanner.Err(); scanErr != nil {
handler.OnScanErr(state, scanErr)
}
}
func isEOF(r []rune, i int) bool {
return i == len(r)
}
// ParseCommand parses a command of the form "COMMAND ARG1 ... ARGN".
// Examples:
//
// foo bar is the command "foo" with argument "bar". Arguments might also
// be enclosed in quotes, so foo "bar bar" is parsed as command foo with
// argument bar bar (a single argument).
func ParseCommand(s string) ([]string, error) {
parseErr := errors.New("error parsing command line")
res := make([]string, 0)
// basically this is an deterministic automaton, however I can't share my
// "nice" image with you
// the following 3 variables mean:
// state is the state of the automaton, we have 5 states
// i is the index in the position in s in which to apply the state function
// start is the start of the argument (when we're finished parsing one)
// however, we don't work on the string but on runes
r := []rune(s)
state, i := 0, 0
// while parsing runes get appended here to build the current argument
currentArg := make([]rune, 0)
// now iterate over each rune
L:
for ; i <= len(r); i++ {
switch state {
case 0:
// state when we parse a new command, that means currentArg must be empty
if isEOF(r, i) {
// done parsing
break L
}
switch r[i] {
case ' ':
// do nothing, just remain in state
case '\\':
state = 2
case '"':
state = 3
default:
currentArg = append(currentArg, r[i])
state = 1
}
case 1:
// state where we parse an argument not enclosed in ""
if isEOF(r, i) {
break L
}
switch r[i] {
case ' ':
// parsing done
res = append(res, string(currentArg))
currentArg = nil
state = 0
case '\\':
state = 2
case '"':
return nil, parseErr
default:
//remain in state, append rune
currentArg = append(currentArg, r[i])
}
case 2:
// state where we previously parsed a \, so know we must parse either "
// \
if isEOF(r, i) {
return nil, parseErr
}
switch r[i] {
case '\\', '"':
// add to current arg and switch back to state 1
currentArg = append(currentArg, r[i])
state = 1
default:
return nil, parseErr
}
case 3:
// state where we parse an argument enclosed in ""
if isEOF(r, i) {
return nil, parseErr
}
switch r[i] {
case '"':
// parsing done
res = append(res, string(currentArg))
currentArg = nil
state = 0
case '\\':
state = 4
default:
currentArg = append(currentArg, r[i])
}
case 4:
// state where we previously parsed a \, so know we must parse either "
// \
// Similar to state 2, but know we reached the state from an arg
// enclosed in ""
if isEOF(r, i) {
return nil, parseErr
}
switch r[i] {
case '\\', '"':
// add to current arg and switch back to state 3
currentArg = append(currentArg, r[i])
state = 3
default:
return nil, parseErr
}
}
}
// now something might still be there (just a break in the loop, not adding
// to res)
if len(currentArg) > 0 {
res = append(res, string(currentArg))
}
return res, nil
}
// PwdCommand is a command that prints the current working directory.
func PwdCommand(state *ExecutorState, args ...string) error {
fmt.Fprintln(state.Out, state.WorkingDir)
return nil
}
// StatsCommand is a command that prints variable / value pairs.
func StatsCommand(state *ExecutorState, args ...string) error {
m := map[string]interface{}{
"routines": state.NumRoutines,
"verbose": state.Verbose,
"cut": state.CutMosaic,
"jpeg-quality": state.JPGQuality,
"interp": InterPString(state.InterP),
"cache": state.CacheSize,
"variety": state.VarietySelector.DisplayString(),
"best": fmt.Sprintf("%.2f %%", 100.0*state.BestFit),
}
if len(args) == 1 {
// print specific value
if val, has := m[args[0]]; has {
fmt.Fprintf(state.Out, "%s ==> %v\n", args[0], val)
} else {
return fmt.Errorf("unkown variable %s", args[0])
}
} else {
// print all values
// keep order deterministic
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, variable := range keys {
val := m[variable]
fmt.Fprintf(state.Out, "%s ==> %v\n", variable, val)
}
}
return nil
}
// SetVarCommand sets a variable to a new value.
func SetVarCommand(state *ExecutorState, args ...string) error {
if len(args) != 2 {
return errors.New("invalid set syntax: Requires variable and value. For a list of variables use \"stats\"")
}
name, valueStr := args[0], args[1]
switch name {
case "routines":
val, parseErr := strconv.Atoi(valueStr)
if parseErr != nil {
return fmt.Errorf("invalid value for routines (must be positive int): %s", parseErr.Error())
}
if val <= 0 {
return fmt.Errorf("invalid value for routines (must be positive int): %d", val)
}
state.NumRoutines = val
return nil
case "verbose":
val, parseErr := strconv.ParseBool(valueStr)
if parseErr != nil {
return fmt.Errorf("invalid value for verbose (must be true or false): %s", parseErr.Error())
}
state.Verbose = val
return nil
case "cut":
val, parseErr := strconv.ParseBool(valueStr)
if parseErr != nil {
return fmt.Errorf("invalid value for cut (must be true or false): %s", parseErr.Error())
}
state.CutMosaic = val
return nil
case "jpeg-quality":
val, parseErr := strconv.Atoi(valueStr)
if parseErr != nil {
return fmt.Errorf("invalid value for jpeg-quality (must be int between 1 and 100): %s", parseErr.Error())
}
if val < 1 || val > 100 {
return fmt.Errorf("invalid value for jpeg-quality (must be int between 1 and 100): %d", val)
}
state.JPGQuality = val
return nil
case "interp":
val, parseErr := strconv.Atoi(valueStr)
if parseErr != nil {
return fmt.Errorf("invalid value for interpolation function, must be integer >= 0: %s", parseErr.Error())
}
if val < 0 {
return fmt.Errorf("invalid value for interpolation function, must be integer >= 0: %d", val)
}
interP := GetInterP(uint(val))
state.InterP = interP
return nil
case "cache":
val, parseErr := strconv.Atoi(valueStr)
if parseErr != nil {
return fmt.Errorf("invalid value for cache size, must be an integer: %d", val)
}
state.CacheSize = val
return nil
case "variety":
val, parseErr := ParseCMDVarietySelector(valueStr)
if parseErr != nil {
return fmt.Errorf("invalid value for variety, must be \"None\" or \"Random\", got: \"%s\"", valueStr)
}
state.VarietySelector = val
return nil
case "best":
val, parseErr := ParsePercent(valueStr)
if parseErr != nil {
return fmt.Errorf("invalid value for best, must be a percent (50.0%% or 0.5), got %s", valueStr)
}
state.BestFit = val
return nil
default:
return fmt.Errorf("invalid variable \"%s\". For a list use \"stats\"", name)
}
}
// CdCommand is a command that changes the current directory.
func CdCommand(state *ExecutorState, args ...string) error {
if len(args) != 1 {
return ErrCmdSyntaxErr
}
path := args[0]
var expandErr error
path, expandErr = homedir.Expand(path)
if expandErr != nil {
return fmt.Errorf("changing directory failed: %s", expandErr.Error())
}
if fi, err := os.Lstat(path); err != nil {
return fmt.Errorf("changing directory failed: %s", err.Error())
} else {
if !fi.IsDir() {
return fmt.Errorf("changing directory failed: \"%s\" is not a directory", path)
} else {
// convert to absolute path
abs, absErr := filepath.Abs(path)
if absErr != nil {
return fmt.Errorf("changing directory failed: %s", absErr.Error())
} else {
state.WorkingDir = abs
return nil
}
}
}
}
// ImageStorageCommand is a command that executes tasks with the fs mapper
// and therefor the image storage (the user doesn't need to know about details
// as mapper and storage, so it's simply called storage).
// This command without arguments just prints the number of databases in the
// storage.
// With the single argument "list" it prints the path of each image in the
// storage.
// With the argument "load" a second argument "DIR" is required, this will
// load all images from the directory in the storage. If a third argument
// is provided this must be a bool that is true if the directory should be
// scanned recursively. The default is not to scan recursively.
//
// Note that jpg and png files are considered valid image types, thus
// image.jpeg and image.png should be included if you're planning to use
// this function.
func ImageStorageCommand(state *ExecutorState, args ...string) error {
switch {
case len(args) == 0:
fmt.Fprintln(state.Out, "Number of database images:", state.Mapper.Len())
return nil
case args[0] == "list":
for _, path := range state.Mapper.IDMapping {
fmt.Fprintf(state.Out, " %s\n", path)
}
fmt.Fprintln(state.Out, "Total:", state.Mapper.Len())
return nil
case args[0] == "load":
var dir string
var recursive bool
switch {
case len(args) == 1:
dir = state.WorkingDir
case len(args) > 2:
// parse recursive flag
var boolErr error
recursive, boolErr = strconv.ParseBool(args[2])
if boolErr != nil {
return boolErr
}
// parse path argument
fallthrough
case len(args) > 1:
// parse the path
var pathErr error
dir, pathErr = state.GetPath(args[1])
if pathErr != nil {
return pathErr
}
default:
// just to be sure, should never happen
return nil
}
fmt.Fprintln(state.Out, "Loading images from", dir)
if recursive {
fmt.Fprintln(state.Out, "Recursive mode enabled")
}
state.Mapper.Clear()
// make gchs invalid
state.GCHStorage = nil
// make lchs invalid
state.LCHStorage = nil
if loadErr := state.Mapper.Load(dir, recursive, JPGAndPNG); loadErr != nil {
state.Mapper.Clear()
// should not be necessary, just to follow the pattern
state.GCHStorage = nil
state.LCHStorage = nil
return loadErr
}
fmt.Fprintln(state.Out, "Successfully read", state.Mapper.Len(), "images")
fmt.Fprintln(state.Out, "Don't forget to (re)load precomputed data if required!")
return nil
default:
return ErrCmdSyntaxErr
}
}
// TODO stuff here should be moved to other functions to avoid repeating code
// later...
// GCHCommand can create histograms for all images in storage, save and load
// files.
func GCHCommand(state *ExecutorState, args ...string) error {
switch {
case len(args) == 0:
return ErrCmdSyntaxErr
case args[0] == "create":
// k is the number of subdivions, defaults to 8
var k uint = 8
if len(args) > 1 {
asInt, parseErr := strconv.Atoi(args[1])
if parseErr != nil {
return parseErr
}
// validate k: must be >= 1 and <= 256
if asInt < 1 || asInt > 256 {
return fmt.Errorf("k for GCH must be a value between 1 and 256, got %d", asInt)
}
k = uint(asInt)
}
// create all histograms
fmt.Fprintf(state.Out, "Creating histograms for all images in storage with k = %d sub-divisions\n", k)
var progress ProgressFunc
if state.Verbose {
inStore := int(state.ImgStorage.NumImages())
progress = StdProgressFunc(state.Out, "",
inStore, IntMin(100, inStore/10))
}
start := time.Now()
histograms, histErr := CreateAllHistograms(state.ImgStorage,
true, k, state.NumRoutines, progress)
execTime := time.Since(start)
if histErr != nil {
return histErr
}
// set histograms
state.GCHStorage = &MemoryHistStorage{Histograms: histograms, K: k}
fmt.Fprintf(state.Out, "Computed %d histograms in %v\n", len(histograms), execTime)
return nil
case args[0] == "save":
if state.GCHStorage == nil {
return errors.New("No GCHs loaded yet")
}
// save ~/bla.[json|gob]
// save ~/
if len(args) < 2 {
return ErrCmdSyntaxErr
}
path, pathErr := state.GetPath(args[1])
if pathErr != nil {
return pathErr
}
// check if path is a file or directory
// we don't report the fiErr (this is not nil if file doesn't exist which
// is of course allowed)
fi, fiErr := os.Lstat(path)
if fiErr == nil && fi.IsDir() {
// save with default naming scheme in that directory
name := GCHFileName(state.GCHStorage.K, "gob")
path = filepath.Join(path, name)
}
controller, creationErr := CreateHistFSController(IDList(state.ImgStorage),
state.Mapper, state.GCHStorage)
if creationErr != nil {
return creationErr
}
// save file
saveErr := controller.WriteFile(path)
if saveErr == nil {
// ignore write error here
fmt.Fprintln(state.Out, "Successfully wrote", state.ImgStorage.NumImages(), "histograms",
"to", path)
}
return saveErr
case args[0] == "load":
if len(args) < 2 {
return ErrCmdSyntaxErr
}
path, pathErr := state.GetPath(args[1])
if pathErr != nil {
return pathErr
}
controller := HistogramFSController{}
readErr := controller.ReadFile(path)
if readErr != nil {
return readErr
}
fmt.Fprintf(state.Out, "Read %d histograms\n", len(controller.Entries))
// we don't care about missing / new images, we just print a warning if
// the lengths have change.
if len(controller.Entries) != int(state.ImgStorage.NumImages()) {
fmt.Fprintln(state.Out, "Unmatched number of images in storage and loaded histograms.",
"Have the images changed? In this case the histograms must be re-computed.")
}
memStorage, createErr := MemHistStorageFromFSMapper(state.Mapper, &controller, nil)
if createErr != nil {
return createErr
}
state.GCHStorage = memStorage
fmt.Fprintln(state.Out, "Histograms have been mapped to image store.")
return nil
default:
return ErrCmdSyntaxErr
}
}
func LCHCommand(state *ExecutorState, args ...string) error {
switch {
case len(args) == 0:
return ErrCmdSyntaxErr
case args[0] == "create":
if len(args) < 3 {
return ErrCmdSyntaxErr
}
// k is the number of subdivions
asInt, parseErr := strconv.Atoi(args[1])
if parseErr != nil {
return parseErr
}
// validate k: must be >= 1 and <= 256
if asInt < 1 || asInt > 256 {
return fmt.Errorf("k for LCH must be a value between 1 and 256, got %d", asInt)
}
k := uint(asInt)
// parse scheme size
asInt, parseErr = strconv.Atoi(args[2])
if parseErr != nil {
return parseErr
}
// now create lch scheme
var scheme LCHScheme
switch asInt {
case 4:
scheme = NewFourLCHScheme()
case 5:
scheme = NewFiveLCHScheme()
default:
return fmt.Errorf("Invalid scheme size %d: Supported are 4 and 5", asInt)
}
// create all lchs
fmt.Fprintf(state.Out, "Creating LCHs for all images in storage with k = %d sub-divisions and %d parts\n", k, asInt)
var progress ProgressFunc
if state.Verbose {
inStore := int(state.ImgStorage.NumImages())
progress = StdProgressFunc(state.Out, "",
inStore, IntMin(100, inStore/10))
}
start := time.Now()
lchs, lchsErr := CreateAllLCHs(scheme, state.ImgStorage,
true, k, state.NumRoutines, progress)
execTime := time.Since(start)
if lchsErr != nil {
return lchsErr
}
// set
state.LCHStorage = &MemoryLCHStorage{
LCHs: lchs,
K: k,
Size: uint(asInt),
}
fmt.Fprintf(state.Out, "Computed %d LCHs in %v\n", len(lchs), execTime)
return nil
case args[0] == "save":
if state.LCHStorage == nil {
return errors.New("No LCHs loaded yet")
}
if len(args) < 2 {
return ErrCmdSyntaxErr
}
path, pathErr := state.GetPath(args[1])
if pathErr != nil {
return pathErr
}
// check if path is a file or directory
// we don't report the fiErr (this is not nil if file doesn't exist which
// is of course allowed)
fi, fiErr := os.Lstat(path)
if fiErr == nil && fi.IsDir() {
// save with default naming scheme in that directory
name := LCHFileName(state.LCHStorage.K, state.LCHStorage.Size, "gob")
path = filepath.Join(path, name)
}
controller, creationErr := CreateLCHFSController(IDList(state.ImgStorage),
state.Mapper, state.LCHStorage)
if creationErr != nil {
return creationErr
}
// save file
saveErr := controller.WriteFile(path)
if saveErr == nil {
fmt.Fprintln(state.Out, "Successfully wrote", state.ImgStorage.NumImages(),
"LCHs to", path)
}
return saveErr
case args[0] == "load":
if len(args) < 2 {
return ErrCmdSyntaxErr
}
path, pathErr := state.GetPath(args[1])
if pathErr != nil {
return pathErr
}
controller := LCHFSController{}
readErr := controller.ReadFile(path)
if readErr != nil {
return readErr
}
fmt.Fprintf(state.Out, "Read %d LCHs\n", len(controller.Entries))
// we don't care about missing / new images, we just print a warning if
// the lengths have change.
if len(controller.Entries) != int(state.ImgStorage.NumImages()) {
fmt.Fprintln(state.Out, "Unmachted number of images in storage and loaded",
"LCHs. Have the images changed? In this case the LCHs must be re-computed.")
}
memStorage, createErr := MemLCHStorageFromFSMapper(state.Mapper, &controller, nil)
if createErr != nil {
return createErr
}
// set
state.LCHStorage = memStorage
fmt.Fprintln(state.Out, "LCHs have been mapped to image store.")
return nil
default:
return ErrCmdSyntaxErr
}
}
func parseGCHMetric(s string) (HistogramMetric, error) {
var metricName string
switch {
case s == "gch":
metricName = "euclid"
case strings.HasPrefix(s, "gch-"):
metricName = s[4:]
default:
return nil, fmt.Errorf("Invalid gch format, expect \"gch\" or \"gch-<metric>\", got %s", s)
}
if metric, ok := GetHistogramMetric(metricName); ok {
return metric, nil
}
return nil, fmt.Errorf("Unkown metric %s", metricName)
}
func parseLCHMetric(s string) (HistogramMetric, error) {
var metricName string
switch {
case s == "lch":
metricName = "euclid"
case strings.HasPrefix(s, "lch-"):
metricName = s[4:]
default:
return nil, fmt.Errorf("Invalid lch format, expect \"lch\" or \"lch-<metric>\", got %s", s)
}
if metric, ok := GetHistogramMetric(metricName); ok {
return metric, nil
}
return nil, fmt.Errorf("Unkown metric %s", metricName)
}
func saveImage(file string, img image.Image, jpgQuality int) error {
outFile, outErr := os.Create(file)
if outErr != nil {
return outErr
}
defer outFile.Close()
var encErr error
ext := filepath.Ext(file)
switch strings.ToLower(ext) {
case ".jpg", ".jpeg":
encErr = jpeg.Encode(outFile, img, &jpeg.Options{Quality: jpgQuality})
case ".png":
encErr = png.Encode(outFile, img)
default:
// this should not happen...
return fmt.Errorf("Unsupported file type: %s, expected .jpg or .png", ext)
}
return encErr
}
// MosaicCommand creates a mosaic images.
// For details see the entry created in the init() method / the description
// text of the command our the online documentation. Usage example:
// mosaic in.jpg out.jpg gch-cosine 20x30 1024x768
func MosaicCommand(state *ExecutorState, args ...string) error {
// mosaic in.png out.png gch-... tilesXxtilesY [outDimensions]
if int(state.ImgStorage.NumImages()) == 0 {
return errors.New("No images in storage, use \"storage load\"")
}
switch {
case len(args) > 3:
totalStart := time.Now()
if !JPGAndPNG(filepath.Ext(args[1])) {
return fmt.Errorf("Supported files are .jpg and .png, got file %s", args[1])
}
// get out path
outPath, outPathErr := state.GetPath(args[1])
if outPathErr != nil {
return outPathErr
}
selectionStr := args[2]
// supported gch and lch
useGCH := true
// try to parse gch and lch
// not so nice, we compute prefix stuff later again... but well
switch {
case strings.HasPrefix(selectionStr, "gch"):
useGCH = true
if state.GCHStorage == nil {
return errors.New("No GCH data loaded, use \"gch create\" or \"gch load\"")
}
case strings.HasPrefix(selectionStr, "lch"):
useGCH = false
if state.LCHStorage == nil {
return errors.New("No LCH data loaded, use \"lch create\" or \"lch load\"")
}
default:
return fmt.Errorf("Invalid image selector, expected gch or lch, got %s", selectionStr)
}
tilesX, tilesY, tilesParseErr := ParseDimensions(args[3])
if tilesParseErr != nil {
return ErrCmdSyntaxErr
}
if tilesX == 0 || tilesY == 0 {
return fmt.Errorf("Tiles dimensions are not allowed to be empty, got %s", args[3])
}