forked from diz-vara/image
-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.lua
executable file
·1779 lines (1656 loc) · 58.8 KB
/
init.lua
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 (c) 2011 Ronan Collobert, Clement Farabet
--
-- Permission is hereby granted, free of charge, to any person obtaining
-- a copy of this software and associated documentation files (the
-- "Software"), to deal in the Software without restriction, including
-- without limitation the rights to use, copy, modify, merge, publish,
-- distribute, sublicense, and/or sell copies of the Software, and to
-- permit persons to whom the Software is furnished to do so, subject to
-- the following conditions:
--
-- The above copyright notice and this permission notice shall be
-- included in all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-- LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-- OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--
----------------------------------------------------------------------
-- description:
-- image - an image toolBox, for Torch
--
-- history:
-- July 1, 2011, 7:42PM - import from Torch5 - Clement Farabet
----------------------------------------------------------------------
require 'torch'
require 'sys'
require 'xlua'
require 'dok'
require 'libimage'
----------------------------------------------------------------------
-- types lookups
--
local type2tensor = {
float = torch.FloatTensor(),
double = torch.DoubleTensor(),
byte = torch.ByteTensor(),
}
local template = function(type)
if type then
return type2tensor[type]
else
return torch.Tensor()
end
end
----------------------------------------------------------------------
-- save/load in multiple formats
--
local function loadPNG(filename, depth, tensortype)
if not xlua.require 'libpng' then
dok.error('libpng package not found, please install libpng','image.loadPNG')
end
local MAXVAL = 255
local a = template(tensortype).libpng.load(filename)
if tensortype ~= 'byte' then
a:mul(1/MAXVAL)
end
if depth and depth == 1 then
if a:nDimension() == 2 then
-- all good
elseif a:size(1) == 3 or a:size(1) == 4 then
a = image.rgb2y(a:narrow(1,1,3))[1]
elseif a:size(1) == 2 then
a = a:narrow(1,1,1)
elseif a:size(1) ~= 1 then
dok.error('image loaded has wrong #channels','image.loadPNG')
end
elseif depth and depth == 3 then
if a:size(1) == 3 then
-- all good
elseif a:size(1) == 4 then
a = a:narrow(1,1,3)
else
dok.error('image loaded has wrong #channels','image.loadPNG')
end
end
return a
end
rawset(image, 'loadPNG', loadPNG)
local function savePNG(filename, tensor)
if not xlua.require 'libpng' then
dok.error('libpng package not found, please install libpng','image.savePNG')
end
local MAXVAL = 255
local a = torch.Tensor():resize(tensor:size()):copy(tensor)
a.image.saturate(a) -- bound btwn 0 and 1
a:mul(MAXVAL) -- remap to [0..255]
a.libpng.save(filename, a)
end
rawset(image, 'savePNG', savePNG)
function image.getPNGsize(filename)
if not xlua.require 'libpng' then
dok.error('libpng package not found, please install libpng','image.getPNGsize')
end
return torch.Tensor().libpng.size(filename)
end
local function processJPG(img, depth, tensortype)
local MAXVAL = 255
if tensortype ~= 'byte' then
img:mul(1/MAXVAL)
end
if depth and depth == 1 then
if img:nDimension() == 2 then
-- all good
elseif img:size(1) == 3 or img:size(1) == 4 then
img = image.rgb2y(img:narrow(1,1,3))[1]
elseif img:size(1) == 2 then
img = img:narrow(1,1,1)
elseif img:size(1) ~= 1 then
dok.error('image loaded has wrong #channels','processJPG')
end
elseif depth and depth == 3 then
if img:size(1) == 3 then
-- all good
elseif img:size(1) == 4 then
img = img:narrow(1,1,3)
else
dok.error('image loaded has wrong #channels','processJPG')
end
end
return img
end
local function loadJPG(filename, depth, tensortype)
if not xlua.require 'libjpeg' then
dok.error('libjpeg package not found, please install libjpeg','image.loadJPG')
end
local load_from_file = 1
local a = template(tensortype).libjpeg.load(load_from_file, filename)
if a == nil then
return nil
else
return processJPG(a, depth, tensortype)
end
end
rawset(image, 'loadJPG', loadJPG)
local function decompressJPG(tensor, depth, tensortype)
if not xlua.require 'libjpeg' then
dok.error('libjpeg package not found, please install libjpeg',
'image.decompressJPG')
end
if torch.typename(tensor) ~= 'torch.ByteTensor' then
dok.error('Input tensor (with compressed jpeg) must be a byte tensor',
'image.decompressJPG')
end
local load_from_file = 0
local a = template(tensortype).libjpeg.load(load_from_file, tensor)
if a == nil then
return nil
else
return processJPG(a, depth, tensortype)
end
end
rawset(image, 'decompressJPG', decompressJPG)
local function saveJPG(filename, tensor)
if not xlua.require 'libjpeg' then
dok.error('libjpeg package not found, please install libjpeg','image.saveJPG')
end
local MAXVAL = 255
local a = torch.Tensor():resize(tensor:size()):copy(tensor)
a.image.saturate(a) -- bound btwn 0 and 1
a:mul(MAXVAL) -- remap to [0..255]
a.libjpeg.save(filename, a)
end
rawset(image, 'saveJPG', saveJPG)
function image.getJPGsize(filename)
if not xlua.require 'libjpeg' then
dok.error('libjpeg package not found, please install libjpeg','image.getJPGsize')
end
return torch.Tensor().libjpeg.size(filename)
end
local function loadPPM(filename, depth, tensortype)
require 'libppm'
local MAXVAL = 255
local a = template(tensortype).libppm.load(filename)
if tensortype ~= 'byte' then
a:mul(1/MAXVAL)
end
if depth and depth == 1 then
if a:nDimension() == 2 then
-- all good
elseif a:size(1) == 3 or a:size(1) == 4 then
a = image.rgb2y(a:narrow(1,1,3))[1]
elseif a:size(1) == 2 then
a = a:narrow(1,1,1)
elseif a:size(1) ~= 1 then
dok.error('image loaded has wrong #channels','image.loadPPM')
end
elseif depth and depth == 3 then
if a:size(1) == 3 then
-- all good
elseif a:size(1) == 4 then
a = a:narrow(1,1,3)
else
dok.error('image loaded has wrong #channels','image.loadPPM')
end
end
return a
end
rawset(image, 'loadPPM', loadPPM)
local function savePPM(filename, tensor)
require 'libppm'
if tensor:nDimension() ~= 3 or tensor:size(1) ~= 3 then
dok.error('can only save 3xHxW images as PPM', 'image.savePPM')
end
local MAXVAL = 255
local a = torch.Tensor():resize(tensor:size()):copy(tensor)
a.image.saturate(a) -- bound btwn 0 and 1
a:mul(MAXVAL) -- remap to [0..255]
a.libppm.save(filename, a)
end
rawset(image, 'savePPM', savePPM)
local function savePGM(filename, tensor)
require 'libppm'
if tensor:nDimension() == 3 and tensor:size(1) ~= 1 then
dok.error('can only save 1xHxW or HxW images as PGM', 'image.savePGM')
end
local MAXVAL = 255
local a = torch.Tensor():resize(tensor:size()):copy(tensor)
a.image.saturate(a) -- bound btwn 0 and 1
a:mul(MAXVAL) -- remap to [0..255]
a.libppm.save(filename, a)
end
rawset(image, 'savePGM', savePGM)
local filetypes = {
jpg = {loader = image.loadJPG, saver = image.saveJPG},
png = {loader = image.loadPNG, saver = image.savePNG},
ppm = {loader = image.loadPPM, saver = image.savePPM},
pgm = {loader = image.loadPGM, saver = image.savePGM}
}
filetypes['JPG'] = filetypes['jpg']
filetypes['JPEG'] = filetypes['jpg']
filetypes['jpeg'] = filetypes['jpg']
filetypes['PNG'] = filetypes['png']
filetypes['PPM'] = filetypes['ppm']
filetypes['PGM'] = filetypes['pgm']
rawset(image, 'supported_filetypes', filetypes)
local function is_supported(suffix)
return filetypes[suffix] ~= nil
end
rawset(image, 'is_supported', is_supported)
local function load(filename, depth, tensortype)
if not filename then
print(dok.usage('image.load',
'loads an image into a torch.Tensor', nil,
{type='string', help='path to file', req=true},
{type='number', help='force destination depth: 1 | 3'},
{type='string', help='type: byte | float | double'}))
dok.error('missing file name', 'image.load')
end
local ext = string.match(filename,'%.(%a+)$')
local tensor
if image.is_supported(ext) then
tensor = filetypes[ext].loader(filename, depth, tensortype)
else
dok.error('unknown image type: ' .. ext, 'image.load')
end
return tensor
end
rawset(image, 'load', load)
local function save(filename, tensor)
if not filename or not tensor then
print(dok.usage('image.save',
'saves a torch.Tensor to a disk', nil,
{type='string', help='path to file', req=true},
{type='torch.Tensor', help='tensor to save (NxHxW, N = 1 | 3)'}))
dok.error('missing file name | tensor to save', 'image.save')
end
local ext = string.match(filename,'%.(%a+)$')
if image.is_supported(ext) then
tensor = filetypes[ext].saver(filename, tensor)
else
dok.error('unknown image type: ' .. ext, 'image.save')
end
end
rawset(image, 'save', save)
----------------------------------------------------------------------
-- crop
--
local function crop(...)
local dst,src,startx,starty,endx,endy
local args = {...}
if select('#',...) == 6 then
dst = args[1]
src = args[2]
startx = args[3]
starty = args[4]
endx = args[5]
endy = args[6]
elseif select('#',...) == 5 then
src = args[1]
startx = args[2]
starty = args[3]
endx = args[4]
endy = args[5]
elseif select('#',...) == 4 then
dst = args[1]
src = args[2]
startx = args[3]
starty = args[4]
elseif select('#',...) == 3 then
src = args[1]
startx = args[2]
starty = args[3]
else
print(dok.usage('image.crop',
'crop an image', nil,
{type='torch.Tensor', help='input image', req=true},
{type='number', help='start x', req=true},
{type='number', help='start y', req=true},
{type='number', help='end x'},
{type='number', help='end y'},
'',
{type='torch.Tensor', help='destination', req=true},
{type='torch.Tensor', help='input image', req=true},
{type='number', help='start x', req=true},
{type='number', help='start y', req=true},
{type='number', help='end x'},
{type='number', help='end y'}))
dok.error('incorrect arguments', 'image.crop')
end
if endx==nil then
return src.image.cropNoScale(src,dst,startx,starty)
else
local depth=1
local x
if src:nDimension() > 2 then
x = src.new(src:size(1),endy-starty,endx-startx)
else
x = src.new(endy-starty,endx-startx)
end
src.image.cropNoScale(src,x,startx,starty)
dst = dst or src.new():resizeAs(x)
image.scale(dst,x)
end
return dst
end
rawset(image, 'crop', crop)
----------------------------------------------------------------------
-- translate
--
local function translate(...)
local dst,src,x,y
local args = {...}
if select('#',...) == 4 then
dst = args[1]
src = args[2]
x = args[3]
y = args[4]
elseif select('#',...) == 3 then
src = args[1]
x = args[2]
y = args[3]
else
print(dok.usage('image.translate',
'translate an image', nil,
{type='torch.Tensor', help='input image', req=true},
{type='number', help='horizontal translation', req=true},
{type='number', help='vertical translation', req=true},
'',
{type='torch.Tensor', help='destination', req=true},
{type='torch.Tensor', help='input image', req=true},
{type='number', help='horizontal translation', req=true},
{type='number', help='vertical translation', req=true}))
dok.error('incorrect arguments', 'image.translate')
end
dst = dst or src.new()
dst:resizeAs(src)
dst:zero()
src.image.translate(src,dst,x,y)
return dst
end
rawset(image, 'translate', translate)
----------------------------------------------------------------------
-- scale
--
local function scale(...)
local dst,src,width,height,mode,size
local args = {...}
if select('#',...) == 4 then
src = args[1]
width = args[2]
height = args[3]
mode = args[4]
elseif select('#',...) == 3 then
if type(args[3]) == 'string' then
if type(args[2]) == 'string' or type(args[2]) == 'number' then
src = args[1]
size = args[2]
mode = args[3]
else
dst = args[1]
src = args[2]
mode = args[3]
end
else
src = args[1]
width = args[2]
height = args[3]
end
elseif select('#',...) == 2 then
if type(args[2]) == 'string' or type(args[2]) == 'number' then
src = args[1]
size = args[2]
else
dst = args[1]
src = args[2]
end
else
print(dok.usage('image.scale',
'rescale an image (geometry)', nil,
{type='torch.Tensor', help='input image', req=true},
{type='number', help='destination width', req=true},
{type='number', help='destination height', req=true},
{type='string', help='mode: bilinear | simple', default='bilinear'},
'',
{type='torch.Tensor', help='input image', req=true},
{type='string | number', help='destination size: "WxH" or "MAX" or "^MIN" or MAX', req=true},
{type='string', help='mode: bilinear | simple', default='bilinear'},
'',
{type='torch.Tensor', help='destination image', req=true},
{type='torch.Tensor', help='input image', req=true},
{type='string', help='mode: bilinear | simple', default='bilinear'}))
dok.error('incorrect arguments', 'image.scale')
end
if size then
local iwidth,iheight
if src:nDimension() == 3 then
iwidth,iheight = src:size(3),src:size(2)
else
iwidth,iheight = src:size(2),src:size(1)
end
local imax = math.max(iwidth,iheight)
local omax = tonumber(size)
if omax then
height = iheight / imax * omax
width = iwidth / imax * omax
else
width,height = size:gfind('(%d*)x(%d*)')()
if not width or not height then
local imin = math.min(iwidth,iheight)
local omin = size:gfind('%^(%d*)')()
if omin then
height = iheight / imin * omin
width = iwidth / imin * omin
end
end
end
end
if not dst and (not width or not height) then
dok.error('could not find valid dest size', 'image.scale')
end
if not dst then
if src:nDimension() == 3 then
dst = src.new(src:size(1), height, width)
else
dst = src.new(height, width)
end
end
mode = mode or 'bilinear'
if mode=='bilinear' then
src.image.scaleBilinear(src,dst)
elseif mode=='simple' then
src.image.scaleSimple(src,dst)
else
dok.error('mode must be one of: simple | bilinear', 'image.scale')
end
return dst
end
rawset(image, 'scale', scale)
----------------------------------------------------------------------
-- rotate
--
local function rotate(...)
local dst,src,theta
local args = {...}
if select('#',...) == 3 then
dst = args[1]
src = args[2]
theta = args[3]
elseif select('#',...) == 2 then
src = args[1]
theta = args[2]
else
print(dok.usage('image.rotate',
'rotate an image by theta radians', nil,
{type='torch.Tensor', help='input image', req=true},
{type='number', help='rotation angle (in radians)', req=true},
'',
{type='torch.Tensor', help='destination', req=true},
{type='torch.Tensor', help='input image', req=true},
{type='number', help='rotation angle (in radians)', req=true}))
dok.error('incorrect arguments', 'image.rotate')
end
dst = dst or src.new()
dst:resizeAs(src)
src.image.rotate(src,dst,theta)
return dst
end
rawset(image, 'rotate', rotate)
----------------------------------------------------------------------
-- warp
--
local function warp(...)
local dst,src,field
local mode = 'bilinear'
local offset_mode = true
local clamp_mode = 'clamp'
local args = {...}
local nargs = select('#',...)
local bad_args = false
if nargs == 2 then
src = args[1]
field = args[2]
elseif nargs >= 3 then
if type(args[3]) == 'string' then
-- No destination tensor
src = args[1]
field = args[2]
mode = args[3]
if nargs >= 4 then offset_mode = args[4] end
if nargs >= 5 then clamp_mode = args[5] end
if nargs >= 6 then bad_args = true end
else
-- With Destination tensor
dst = args[1]
src = args[2]
field = args[3]
if nargs >= 4 then mode = args[4] end
if nargs >= 5 then offset_mode = args[5] end
if nargs >= 6 then clamp_mode = args[6] end
if nargs >= 7 then bad_args = true end
end
end
if bad_args then
print(dok.usage('image.warp',
'warp an image, according to a flow field', nil,
{type='torch.Tensor', help='input image (KxHxW)', req=true},
{type='torch.Tensor', help='(y,x) flow field (2xHxW)', req=true},
{type='string', help='mode: lanczos | bicubic | bilinear | simple', default='bilinear'},
{type='string', help='offset mode (add (x,y) to flow field)', default=true},
{type='string', help='clamp mode: how to handle interp of samples off the input image (clamp | pad)', default='clamp'},
'',
{type='torch.Tensor', help='destination', req=true},
{type='torch.Tensor', help='input image (KxHxW)', req=true},
{type='torch.Tensor', help='(y,x) flow field (2xHxW)', req=true},
{type='string', help='mode: lanczos | bicubic | bilinear | simple', default='bilinear'},
{type='string', help='offset mode (add (x,y) to flow field)', default=true},
{type='string', help='clamp mode: how to handle interp of samples off the input image (clamp | pad)', default='clamp'}))
dok.error('incorrect arguments', 'image.warp')
end
-- This is a little messy, but convert mode string to an enum
if (mode == 'simple') then
mode = 0
elseif (mode == 'bilinear') then
mode = 1
elseif (mode == 'bicubic') then
mode = 2
elseif (mode == 'lanczos') then
mode = 3
else
dok.error('Incorrect arguments (mode is not lanczos | bicubic | bilinear | simple)!', 'image.warp')
end
if (clamp_mode == 'clamp') then
clamp_mode = 0
elseif (clamp_mode == 'pad') then
clamp_mode = 1
else
dok.error('Incorrect arguments (clamp_mode is not clamp | pad)!', 'image.warp')
end
local dim2 = false
if src:nDimension() == 2 then
dim2 = true
src = src:reshape(1,src:size(1),src:size(2))
end
dst = dst or src.new()
dst:resize(src:size(1), field:size(2), field:size(3))
src.image.warp(dst, src, field, mode, offset_mode, clamp_mode)
if dim2 then
dst = dst[1]
end
return dst
end
rawset(image, 'warp', warp)
----------------------------------------------------------------------
-- hflip
--
local function hflip(...)
local dst,src
local args = {...}
if select('#',...) == 2 then
dst = args[1]
src = args[2]
elseif select('#',...) == 1 then
src = args[1]
else
print(dok.usage('image.hflip',
'flips an image horizontally (left/right)', nil,
{type='torch.Tensor', help='input image', req=true},
'',
{type='torch.Tensor', help='destination', req=true},
{type='torch.Tensor', help='input image', req=true}))
dok.error('incorrect arguments', 'image.hflip')
end
dst = dst or src.new()
local original_size = src:size()
if src:nDimension() == 2 then
src = src:new():resize(1,src:size(1),src:size(2))
end
dst:resizeAs(src)
dst.image.hflip(dst, src)
dst:resize(original_size)
return dst
end
rawset(image, 'hflip', hflip)
----------------------------------------------------------------------
-- vflip
--
local function vflip(...)
local dst,src
local args = {...}
if select('#',...) == 2 then
dst = args[1]
src = args[2]
elseif select('#',...) == 1 then
src = args[1]
else
print(dok.usage('image.vflip',
'flips an image vertically (upside-down)', nil,
{type='torch.Tensor', help='input image', req=true},
'',
{type='torch.Tensor', help='destination', req=true},
{type='torch.Tensor', help='input image', req=true}))
dok.error('incorrect arguments', 'image.vflip')
end
dst = dst or src.new()
local original_size = src:size()
if src:nDimension() == 2 then
src = src:new():resize(1,src:size(1),src:size(2))
end
dst:resizeAs(src)
dst.image.vflip(dst, src)
dst:resize(original_size)
return dst
end
rawset(image, 'vflip', vflip)
----------------------------------------------------------------------
-- convolve(dst,src,ker,type)
-- convolve(dst,src,ker)
-- dst = convolve(src,ker,type)
-- dst = convolve(src,ker)
--
local function convolve(...)
local dst,src,kernel,mode
local args = {...}
if select('#',...) == 4 then
dst = args[1]
src = args[2]
kernel = args[3]
mode = args[4]
elseif select('#',...) == 3 then
if type(args[3]) == 'string' then
src = args[1]
kernel = args[2]
mode = args[3]
else
dst = args[1]
src = args[2]
kernel = args[3]
end
elseif select('#',...) == 2 then
src = args[1]
kernel = args[2]
else
print(dok.usage('image.convolve',
'convolves an input image with a kernel, returns the result', nil,
{type='torch.Tensor', help='input image', req=true},
{type='torch.Tensor', help='kernel', req=true},
{type='string', help='type: full | valid | same', default='valid'},
'',
{type='torch.Tensor', help='destination', req=true},
{type='torch.Tensor', help='input image', req=true},
{type='torch.Tensor', help='kernel', req=true},
{type='string', help='type: full | valid | same', default='valid'}))
dok.error('incorrect arguments', 'image.convolve')
end
if mode and mode ~= 'valid' and mode ~= 'full' and mode ~= 'same' then
dok.error('mode has to be one of: full | valid | same', 'image.convolve')
end
local md = (((mode == 'full') or (mode == 'same')) and 'F') or 'V'
if kernel:nDimension() == 2 and src:nDimension() == 3 then
local k3d = src.new(src:size(1), kernel:size(1), kernel:size(2))
for i = 1,src:size(1) do
k3d[i]:copy(kernel)
end
kernel = k3d
end
if dst then
torch.conv2(dst,src,kernel,md)
else
dst = torch.conv2(src,kernel,md)
end
if mode == 'same' then
local cx = dst:dim()
local cy = cx-1
local ofy = math.ceil(kernel:size(cy)/2)
local ofx = math.ceil(kernel:size(cx)/2)
dst = dst:narrow(cy, ofy, src:size(cy)):narrow(cx, ofx, src:size(cx))
end
return dst
end
rawset(image, 'convolve', convolve)
----------------------------------------------------------------------
-- compresses an image between min and max
--
local function minmax(args)
local tensor = args.tensor
local min = args.min
local max = args.max
local symm = args.symm or false
local inplace = args.inplace or false
local saturate = args.saturate or false
local tensorOut = args.tensorOut or (inplace and tensor)
or torch.Tensor(tensor:size()):copy(tensor)
-- resize
if args.tensorOut then
tensorOut:resize(tensor:size()):copy(tensor)
end
-- saturate useless if min/max inferred
if min == nil and max == nil then
saturate = false
end
-- rescale min
local fmin = 0
if (min == nil) then
if args.symm then
fmin = math.max(math.abs(tensorOut:min()),math.abs(tensorOut:max()))
min = -fmin
else
min = tensorOut:min()
end
end
if (min ~= 0) then tensorOut:add(-min) end
-- rescale for max
if (max == nil) then
if args.symm then
max = fmin*2
else
max = tensorOut:max()
end
else
max = max - min
end
if (max ~= 0) then tensorOut:div(max) end
-- saturate
if saturate then
tensorOut.image.saturate(tensorOut)
end
-- and return
return tensorOut
end
rawset(image, 'minmax', minmax)
local function toDisplayTensor(...)
-- usage
local _, input, padding, nrow, scaleeach, min, max, symm, saturate = dok.unpack(
{...},
'image.toDisplayTensor',
'given a pack of tensors, returns a single tensor that contains a grid of all in the pack',
{arg='input',type='torch.Tensor | table', help='input (HxW or KxHxW or Kx3xHxW or list)',req=true},
{arg='padding', type='number', help='number of padding pixels between images', default=0},
{arg='nrow',type='number',help='number of images per row', default=6},
{arg='scaleeach', type='boolean', help='individual scaling for list of images', default=false},
{arg='min', type='number', help='lower-bound for range'},
{arg='max', type='number', help='upper-bound for range'},
{arg='symmetric',type='boolean',help='if on, images will be displayed using a symmetric dynamic range, useful for drawing filters', default=false},
{arg='saturate', type='boolean', help='saturate (useful when min/max are lower than actual min/max', default=true}
)
local packed
if type(input) == 'table' then
-- pack images in single tensor
local ndims = input[1]:dim()
local channels = ((ndims == 2) and 1) or input[1]:size(1)
local height = input[1]:size(ndims-1)
local width = input[1]:size(ndims)
packed = torch.Tensor(#input,channels,height,width)
for i,img in ipairs(input) do
packed[i]:copy(input[i])
end
elseif scaleeach then
packed = torch.Tensor(input:size()):copy(input)
else
packed = input
end
-- scale each
if scaleeach and (
(packed:dim() == 4 and (packed:size(2) == 3 or packed:size(2) == 1))
or
(packed:dim() == 3 and (packed:size(1) ~= 1 and packed:size(1) ~= 3))
) then
for i=1,packed:size(1) do
image.minmax{tensor=packed[i], inplace=true, min=min, max=max, symm=symm, saturate=saturate}
end
end
local grid = torch.Tensor()
if packed:dim() == 4 and (packed:size(2) == 3 or packed:size(2) == 1) then
-- arbitrary number of color images: lay them out on a grid
local nmaps = packed:size(1)
local xmaps = math.min(nrow, nmaps)
local ymaps = math.ceil(nmaps / xmaps)
local height = packed:size(3)+padding
local width = packed:size(4)+padding
grid:resize(packed:size(2), height*ymaps, width*xmaps):fill(packed:max())
local k = 1
for y = 1,ymaps do
for x = 1,xmaps do
if k > nmaps then break end
grid:narrow(2,(y-1)*height+1+padding/2,height-padding):narrow(3,(x-1)*width+1+padding/2,width-padding):copy(packed[k])
k = k + 1
end
end
elseif packed:dim() == 2 or (packed:dim() == 3 and (packed:size(1) == 1 or packed:size(1) == 3)) then
-- Rescale range
image.minmax{tensor=packed, inplace=true, min=min, max=max, symm=symm, saturate=saturate}
return packed
elseif packed:dim() == 3 then
-- arbitrary number of channels: lay them out on a grid
local nmaps = packed:size(1)
local xmaps = math.min(nrow, nmaps)
local ymaps = math.ceil(nmaps / xmaps)
local height = packed:size(2)+padding
local width = packed:size(3)+padding
grid:resize(height*ymaps, width*xmaps):fill(packed:max())
local k = 1
for y = 1,ymaps do
for x = 1,xmaps do
if k > nmaps then break end
grid:narrow(1,(y-1)*height+1+padding/2,height-padding):narrow(2,(x-1)*width+1+padding/2,width-padding):copy(packed[k])
k = k + 1
end
end
else
xerror('packed must be a HxW or KxHxW or Kx3xHxW tensor, or a list of tensors', 'image.toDisplayTensor')
end
if not scaleeach then
image.minmax{tensor=grid, inplace=true, min=min, max=max, symm=symm, saturate=saturate}
end
return grid
end
rawset(image,'toDisplayTensor',toDisplayTensor)
----------------------------------------------------------------------
-- super generic display function
--
local function display(...)
-- usage
local _, input, zoom, min, max, legend, w, ox, oy, scaleeach, gui, offscreen, padding, symm, nrow, saturate = dok.unpack(
{...},
'image.display',
'displays a single image, with optional saturation/zoom',
{arg='image', type='torch.Tensor | table', help='image (HxW or KxHxW or Kx3xHxW or list)', req=true},
{arg='zoom', type='number', help='display zoom', default=1},
{arg='min', type='number', help='lower-bound for range'},
{arg='max', type='number', help='upper-bound for range'},
{arg='legend', type='string', help='legend', default='image.display'},
{arg='win', type='qt window', help='window descriptor'},
{arg='x', type='number', help='x offset (only if win is given)', default=0},
{arg='y', type='number', help='y offset (only if win is given)', default=0},
{arg='scaleeach', type='boolean', help='individual scaling for list of images', default=false},
{arg='gui', type='boolean', help='if on, user can zoom in/out (turn off for faster display)',
default=true},
{arg='offscreen', type='boolean', help='offscreen rendering (to generate images)',
default=false},
{arg='padding', type='number', help='number of padding pixels between images', default=0},
{arg='symmetric',type='boolean',help='if on, images will be displayed using a symmetric dynamic range, useful for drawing filters', default=false},
{arg='nrow',type='number',help='number of images per row', default=6},
{arg='saturate', type='boolean', help='saturate (useful when min/max are lower than actual min/max', default=true}
)
-- dependencies
require 'qt'
require 'qttorch'
require 'qtwidget'
require 'qtuiloader'
input = image.toDisplayTensor{input=input, padding=padding, nrow=nrow, saturate=saturate,
scaleeach=scaleeach, min=min, max=max, symmetric=symm}
-- if 2 dims or 3 dims and 1/3 channels, then we treat it as a single image
if input:nDimension() == 2 or (input:nDimension() == 3 and (input:size(1) == 1 or input:size(1) == 3)) then
-- Compute width
local d = input:nDimension()
local x = input:size(d)*zoom
local y = input:size(d-1)*zoom
-- if gui active, then create interactive window (with zoom, clicks and so on)
if gui and not w and not offscreen then
-- create window context
local closure = w
local hook_resize, hook_mouse
if closure and closure.window and closure.image then
closure.image = input
closure.refresh(x,y)
else
closure = {image=input}
hook_resize = function(wi,he)
local qtimg = qt.QImage.fromTensor(closure.image)
closure.painter:image(0,0,wi,he,qtimg)
collectgarbage()
end
hook_mouse = function(x,y,button)
--local size = closure.window.frame.size:totable()
--size.width =
--size.height =
if button == 'LeftButton' then
elseif button == 'RightButton' then
end
--closure.window.frame.size = qt.QSize(size)
end
closure.window, closure.painter = image.window(hook_resize,hook_mouse)
closure.refresh = hook_resize
end
closure.window.size = qt.QSize{width=x,height=y}
closure.window.windowTitle = legend
closure.window:show()
hook_resize(x,y)
closure.isclosure = true
return closure
else
if offscreen then
w = w or qt.QtLuaPainter(x,y)
else
w = w or qtwidget.newwindow(x,y,legend)
end
if w.isclosure then
-- window was created with gui, just update closure
local closure = w
closure.image = input
local size = closure.window.size:totable()
closure.window.windowTitle = legend
closure.refresh(size.width, size.height)
else
-- if no gui, create plain window, and blit
local qtimg = qt.QImage.fromTensor(input)
w:image(ox,oy,x,y,qtimg)
end
end
else
xerror('image must be a HxW or KxHxW or Kx3xHxW tensor, or a list of tensors', 'image.display')
end
-- return painter
return w
end
rawset(image, 'display', display)
----------------------------------------------------------------------