-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstitch_0.9.6.py
More file actions
3877 lines (3509 loc) · 170 KB
/
stitch_0.9.6.py
File metadata and controls
3877 lines (3509 loc) · 170 KB
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
#!/usr/bin/env python
#
# GIMP plug-in to stitch two images together into a panorama.
#
# Copyright (C) 2005 Thomas R. Metcalf (helicity314-stitch <at> yahoo <dot> com)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# If you find this code useful, you may use PayPal to contribute to future
# free software development efforts (send to helicity314-stitch <at> yahoo <dot> com).
# This is neither required nor expected, but would be appreciated. You will get
# nothing for your money other than the knowledge that you are supporting
# the development of free software.
#
# REQUIREMENTS:
#
# - You must have a version of gimp compiled to include python support.
# - python pygtk module >=2.0
#
# INSTALLATION:
#
# Linux: Copy this file to your gimp plug-in directory, e.g. ~/.gimp-2.2/plug-ins,
# then restart gimp and stitch panorama should appear in the Xtns/Utils
# menu. Make sure the file is executable (chmod +x stitch.py). Also, make
# sure to remove any old versions from your plug-in directory.
# Windows: Likely something similar to Linux, but I don't know for sure since I don't
# run windows. You will have to edit the very first line of this
# file to point to python on your system.
#
# VERSION 0.9.2: Beta test version 2005-May-10
# - Initial public release
# VERSION 0.9.3: Beta test version 2005-May-18
# - Improved blending algorithm
# - Improved implementation of rotation & scale in correlation
# VERSION 0.9.4: Beta test version 2005-May-23
# - Improved the blending algorithm
# VERSION 0.9.5: Beta test version 2005-May-30
# - Improved the color balance algorithm
# - Improved treatment of scaling in correlation.
# - Fixed transform for two control points
# VERSION 0.9.6: Beta test version 2005-June-07
# - Added up/down buttons in control point selector
# - Added color check box in control point selector
'''GIMP plug-in to stitch two images together into a panorama.'''
abort = False
# These should all be standard modules
import sys
import os
import copy
import math
import struct
import time
import gimp
import gimpplugin
from gimpenums import *
import pygtk
pygtk.require('2.0')
import gtk
import cPickle as pickle
#------------ MAIN PLUGIN CLASS
class stitch_plugin(gimpplugin.plugin):
'''The main plugin class defines and installs the stitch_panorama function.'''
version = '0.9.6'
def query(self):
gimp.install_procedure("stitch_panorama",
"Stitch two images together to make a panorama",
"Stitch two images together to make a panorama (ver. " + \
stitch_plugin.version+")",
"Thomas R. Metcalf",
"Thomas R. Metcalf",
"2005",
"<Image>/Filters/ChenYen/Stitch Panorama",
"RGB*, GRAY*",EXTENSION,
[(PDB_INT32, "run-mode", "interactive/noninteractive"),
],
[])
# stitch_panorama is the main routine where all the work is done.
def stitch_panorama(self, mode, image_list=None, control_points=None):
'''Stitch together two images into a panorama.
First get a set of "control points" which define matching
locations in the two images. Then use these control points to
balance the color and warp the images into a third, panoramic
image.'''
if not abort:
if not image_list: image_list = gimp.image_list()
# Select which image is the reference and which is transformed.
image_list=select_images(image_list,mode)
if check_image_list_ok(image_list,mode):
image_list[0].disable_undo()
image_list[1].disable_undo()
# fire up the user interface which does all the work.
panorama = stitch_control_panel(control_points,image_list,mode)
# clean up a bit
for img in image_list:
if img:
img.clean_all()
img.enable_undo()
update_image_layers(img) # is this necessary?
gimp.pdb.gimp_displays_flush()
return panorama
# Pau.
#------------ SUPPORTING CLASS DEFINITIONS
class control_point(object):
'''Each control point gives matching locations in two images.'''
def __init__(self,x1,y1,x2,y2,correlation=None,colorbalance=True):
self.xy = (float(x1),float(y1),float(x2),float(y2))
self.correlation = correlation
self.colorbalance = colorbalance
def x1(self): return self.xy[0]
def y1(self): return self.xy[1]
def x2(self): return self.xy[2]
def y2(self): return self.xy[3]
def cb(self):
try:
colorbalance = self.colorbalance
except AttributeError:
colorbalance = True
return colorbalance
def invert(self):
try:
colorbalance = self.colorbalance
except AttributeError:
colorbalance = True
return control_point(self.x2(),self.y2(),self.x1(),self.y1(),
self.correlation,colorbalance)
minradius = 20.0 # min radius for color averaging
class stitchable(object):
'''Two images and their control points for stitching.'''
def __init__(self,mode,rimage,timage,control_points=None):
self.mode = mode # Mode: interactive/noninteractive
self.rimage = rimage # the reference image object
self.timage = timage # the transformed image object
self.cimage = None # temporary image for correlation
self.dimage = None # temporary image for undistorted image
self.rimglayer = None # main image layer in reference image
self.timglayer = None # main image layer in transformed image
self.rcplayer = None # the reference control point display layer
self.tcplayer = None # the transform control point display layer
self.control_points = control_points # the warping control points
self.panorama = None # the resulting panoramic image
self.rlayer = None # the reference layer in self.panorama
self.tlayer = None # the transformed layer in self.panorama
self.rmask = None # the reference layer mask
self.tmask = None # the transformed layer mask
self.rxy = None # x,y of reference corners [x1,y1,x2,y2]
self.txy = None # x,y of transformed corners [x1,y1,x2,y2]
self.interpolation = INTERPOLATION_CUBIC
self.supersample = 1
self.cpcorrelate = True # correlate control points?
self.recursion_level = 5
self.clip_result = 1 # this must be 1 or gimp will crash (segmentation fault)
self.colorbalance = True # color balance?
self.colorradius = minradius # color radius
self.blend = True # blend edges?
self.blend_fraction = 0.25 # size of blend along edges (fraction of image size)
self.rmdistortion = True # remove distortion?
self.condition_number = None # the condition number of the transform
self.progressbar = None # the progress bar widget
self.update()
def __getitem__(self,index):
'''Make the stitchable class indexable over the control points.'''
return self.control_points[index]
def update(self):
if self.control_points:
self.npoints = len(self.control_points)
rarray,tarray = self.arrays()
self.transform = compute_transform_matrix(rarray,tarray,self)
self.errors = compute_control_point_errors(self)
else:
self.npoints = 0
self.transform = None
self.errors = None
def set_control_points(self,control_points):
'''Se the whole control point list.'''
self.control_points = control_points
self.update()
def add_control_point(self,cp):
'''Add a control point to the control_points list.
The control_point parameter should be of the control_point
class.'''
assert cp.__class__ is control_point, \
'control_point parameter is not an instance of the control_point class.'
if self.control_points:
self.control_points.append(cp)
else:
self.control_points = [cp]
self.update()
def delete_control_point(self,index):
'''Delete a control point from the control point list.'''
if self.control_points:
self.control_points.pop(index)
self.update()
def replace_control_point(self,cp,index):
'''Replace a control point in the control point list.'''
if self.control_points:
if index < len(self.control_points):
self.control_points[index] = cp
self.update()
def move_control_point_up(self,index):
if self.control_points:
if index > 0 and index < self.npoints:
cp1 = self.control_points[index]
cp2 = self.control_points[index-1]
self.control_points[index] = cp2
self.control_points[index-1] = cp1
self.update()
def move_control_point_down(self,index):
if self.control_points:
if index >=0 and index <self.npoints-1:
cp1 = self.control_points[index]
cp2 = self.control_points[index+1]
self.control_points[index] = cp2
self.control_points[index+1] = cp1
self.update()
def inverse_control_points(self):
'''Invert the control point list and return the inverse.'''
inverse = []
for c in self.control_points:
inverse.append(c.invert())
return inverse
def arrays(self):
'''Get the reference and transformed control points as lists.'''
rarray = []
tarray = []
for i in range(self.npoints):
rarray.append([self.control_points[i].x1(),self.control_points[i].y1(),1.0])
tarray.append([self.control_points[i].x2(),self.control_points[i].y2(),1.0])
return (rarray,tarray)
def color(self,control_point,radius=minradius):
'''Get the color values at a control point in each image.
The return value is a two-element tuple in which each entry
is a color tuple.'''
assert control_point in self.control_points,'Bad control point'
rnx = self.rimage.width # the dimensions of the images
rny = self.rimage.height
tnx = self.timage.width
tny = self.timage.height
# Make sure that the radius is not so large that the
# average circle extends beyond the edge.
if radius > control_point.x1():
radius = max(control_point.x1(),1.0)
if radius > control_point.y1():
radius = max(control_point.y1(),1.0)
if control_point.x1()+radius > rnx-1:
radius = max(rnx-control_point.x1()-1,1.0)
if control_point.y1()+radius > rny-1:
radius = max(rny-control_point.y1()-1,1.0)
#if __debug__: print 'radius: ',radius,control_point.x1(),control_point.y1(),rnx,rny
# the scale of the transformed image may be different from the scale of the
# reference image. So, the radius should be scaled as well.
if self.transform:
(sscale,srotation) = transform2rs(self.transform)
tradius = max(radius/sscale,1.0)
else:
tradius = radius
# Check size of tradius
if tradius > control_point.x2():
tradius = max(control_point.x2(),1.0)
if self.transform: radius = max(tradius*sscale,1.0)
if tradius > control_point.y2():
tradius = max(control_point.y2(),1.0)
if self.transform: radius = max(tradius*sscale,1.0)
if control_point.x2()+tradius > tnx-1:
tradius = max(tnx-control_point.x2()-1,1.0)
if self.transform: radius = max(tradius*sscale,1.0)
if control_point.y2()+tradius > tny-1:
tradius = max(tny-control_point.y2()-1,1.0)
if self.transform: radius = max(tradius*sscale,1.0)
#if __debug__: print 'radius: ',tradius,control_point.x2(),control_point.y2(),tnx,tny
##if __debug__: print 'color radii are ',radius,tradius
##if __debug__:
## print 'using a color radius of ',radius,tradius
return ( gimp.pdb.gimp_image_pick_color(self.rimage,
self.rimglayer,
control_point.x1(),
control_point.y1(),
0, # use the composite image, ignore the drawable
1,radius),
gimp.pdb.gimp_image_pick_color(self.timage,
self.timglayer,
control_point.x2(),
control_point.y2(),
0, # use the composite image, ignore the drawable
1,tradius)
)
def cbtest(self,control_point):
'''Get the color balance flag for a control point.'''
assert control_point in self.control_points,'Bad control point'
return control_point.cb()
def cbtests(self):
'''Get flag to determine if a control point will be used in the color balancing.'''
return [self.cbtest(self.control_points[c])
for c in range(self.npoints)] # iterates over self.control_points
def colors(self):
'''Get the color values at all the control points.'''
if self.errors:
return [self.color(self.control_points[c],self.colorradius)
for c in range(self.npoints)] # iterates over self.control_points
else:
return [self.color(c) for c in self] # iterates over self.control_points
def brightness(self,control_point,radius=minradius):
'''Compute the brightness of a control point in each image.
The return value is a two-element tuple in which the entries
are the brightness of the two images in the stitchable object.'''
c = self.color(control_point,radius)
brightness1 = 0
brightness2 = 0
n = 0.0
for b1,b2 in zip(c[0],c[1]): # iterate over both image colors simultaneously
brightness1 += b1
brightness2 += b2
n += 1.0
# the brightness is the mean of the values
return (int(round(brightness1/n)),int(round(brightness2/n)))
def brightnesses(self):
'''Get the brightness values at all the control points.'''
if self.errors:
return [self.brightness(self.control_points[c],self.colorradius)
for c in range(self.npoints)] # iterates over self.control_points
else:
return [self.brightness(c) for c in self] # iterates over self.control_points
def value(self,control_point,radius=minradius):
'''Compute the value of a control point in each image.
The return value is a two-element tuple in which the entries
are the value of the two images in the stitchable object.'''
c = self.color(control_point,radius)
# the value is the max of the color channels
return ( max(c[0]), max(c[1]) )
def values(self):
'''Get the values at all the control points.'''
if self.errors:
return [self.value(self.control_points[c],self.colorradius)
for c in range(self.npoints)]
else:
return [self.value(c) for c in self] # iterates over self.control_points
#------------ SUPPORTING MODULE FUNCTIONS
def update_image_layers(image):
'''Update all the layers in an image.'''
for layer in image.layers:
layer.update(0,0,layer.width,layer.height)
layer.flush()
gimp.pdb.gimp_displays_flush()
def error_message(message,mode):
'''Display an error message for the user.'''
if mode == RUN_INTERACTIVE or mode == RUN_WITH_LAST_VALS:
gimp.pdb.gimp_message(message)
else:
print message
def select_images(image_list,mode):
'''Select two of the >2 available images for stitching.
The first in the list is the reference image and the second
is the transformed image.'''
if mode == RUN_NONINTERACTIVE:
return image_list[0:2] # just return the first two
##if __debug__: print 'this is the image selector.'
widget = ImageSelectorWidget(image_list,mode) # make widget
widget.main() # call widget
return widget.image_list
def check_image_list_ok(image_list,mode):
'''Check the image list to make sure it is suitable for stitching.'''
if len(image_list) != 2:
error_message('Error: you must specify two images.',mode)
return False
if not image_list[0] or not image_list[1]:
error_message('Error: you must open at least two images.',mode)
return False
for img in image_list: # Make sure there is something in the images
try:
drawable = gimp.pdb.gimp_image_get_active_drawable(img)
except RuntimeError:
error_message('Error: image '+img.name+' appears to be empty',mode)
return False
if image_list[0] is image_list[1]:
error_message('Warning: you selected the same image as ' + \
'both the reference and the transformed image.',mode)
return True # passed the tests
def stitch_control_panel(control_points,image_list,mode):
'''Instantiate a stitchable object and start the user interface.'''
##if __debug__: print 'this is the stitch user interface.'
# get control points from last run
if not control_points:
control_points = get_control_points_from_parasite(image_list[0],image_list[1])
stitch = stitchable(mode,image_list[0],image_list[1],control_points)
# get the active layer and save for later use. Another layer will be added
# later to mark the control points so we will need to be able to copy
# from just the image layer.
stitch.rimglayer = stitch.rimage.layers[0]
stitch.timglayer = stitch.timage.layers[0]
if len(stitch.rimage.layers) > 1 :
error_message('Warning: your selected reference image has multiple layers. '+\
'Only the bottom layer will be stitched. You may want to '+\
'flatten the image and rerun stitch panorama.',stitch.mode)
if len(stitch.timage.layers) > 1 :
error_message('Warning: your selected transformed image has multiple layers. '+\
'Only the bottom layer will be stitched. You may want to '+\
'flatten the image and rerun stitch panorama.',stitch.mode)
try:
if mode == RUN_NONINTERACTIVE:
go_stitch_panorama(stitch)
else:
# Call the user interface
draw_control_points(stitch)
widget = ControlPanelWidget(stitch)
widget.main()
stitch = widget.stitch
if stitch.control_points:
save_control_points_to_parasite(stitch)
finally:
# clean up a bit
if stitch.panorama: stitch.panorama.enable_undo()
if stitch.rcplayer: stitch.rimage.remove_layer(stitch.rcplayer)
if stitch.tcplayer: stitch.timage.remove_layer(stitch.tcplayer)
if stitch.cimage: gimp.pdb.gimp_image_delete(stitch.cimage)
if stitch.dimage: gimp.pdb.gimp_image_delete(stitch.dimage)
gimp.pdb.gimp_displays_flush()
return stitch.panorama
def control_points_editor(stitch):
'''Set/Edit the control point list.'''
##if __debug__: print 'this is the control points editor'
gimp.pdb.gimp_image_undo_enable(stitch.rimage)
gimp.pdb.gimp_image_undo_enable(stitch.timage)
widget = ControlPointEditorWidget(stitch)
widget.main()
gimp.pdb.gimp_image_undo_disable(stitch.rimage)
gimp.pdb.gimp_image_undo_disable(stitch.timage)
draw_control_points(stitch)
return widget.stitch
def get_new_control_point(stitch,colorbalance=True):
'''Get a new control point from the selections in the images.'''
##if __debug__: print 'this is get_new_control_point()'
reference_selection = gimp.pdb.gimp_selection_bounds(stitch.rimage)
transformed_selection = gimp.pdb.gimp_selection_bounds(stitch.timage)
if not reference_selection[0]:
error_message('Error: there is no selection in the reference image',stitch.mode)
if not transformed_selection[0]:
error_message('Error: there is no selection in the transformed image',stitch.mode)
if not reference_selection[0] or not transformed_selection[0]:
return None
##if __debug__:
## print 'reference selection '+str(reference_selection)
## print 'transformed selection '+str(transformed_selection)
rxsize = reference_selection[3]-reference_selection[1]
rysize = reference_selection[4]-reference_selection[2]
txsize = transformed_selection[3]-transformed_selection[1]
tysize = transformed_selection[4]-transformed_selection[2]
xscale = max(min(rxsize/8.0,txsize/8.0),1.0) # one eighth the max shift
yscale = max(min(rysize/8.0,tysize/8.0),1.0)
# make a temporary image
xsize = max(rxsize,txsize)
ysize = max(rysize,tysize)
rx0 = (xsize-rxsize)/2 # starting coordinates of layer data
ry0 = (ysize-rysize)/2
tx0 = (xsize-txsize)/2
ty0 = (ysize-tysize)/2
##if __debug__: print 'xsize,ysize: ',xsize,ysize,rx0,ry0,rxsize,rysize
if stitch.cimage:
stitch.cimage.resize(xsize,ysize,0,0)
else:
stitch.cimage = gimp.pdb.gimp_image_new(xsize,ysize,RGB)
# Add the reference selection to cimage with a mask
rlayer = gimp.pdb.gimp_layer_new(stitch.cimage, # image
xsize, # width
ysize, # height
RGB, # type
'reference', # name
100, # opacity
NORMAL_MODE # layer combination mode
)
##if __debug__: print stitch.rimglayer,stitch.timglayer
gimp.pdb.gimp_image_add_layer(stitch.cimage,rlayer,-1) # make new layer
foreground = gimp.pdb.gimp_context_get_foreground()
background = gimp.pdb.gimp_context_get_background()
gimp.pdb.gimp_context_set_foreground((0,0,0))
gimp.pdb.gimp_context_set_background((255,255,255))
gimp.pdb.gimp_drawable_fill(rlayer,FOREGROUND_FILL) # erase
gimp.pdb.gimp_edit_copy(stitch.rimglayer) # copy selection
gimp.pdb.gimp_selection_none(stitch.cimage)
gimp.pdb.gimp_rect_select(stitch.cimage,rx0,ry0,rxsize,rysize,CHANNEL_OP_REPLACE,0,0.0)
gimp.pdb.gimp_floating_sel_anchor(gimp.pdb.gimp_edit_paste(rlayer,0)) # paste and anchor
gimp.pdb.gimp_selection_none(stitch.cimage)
gimp.pdb.gimp_layer_add_alpha(rlayer) # Add alpha channel
rmask = gimp.pdb.gimp_layer_create_mask(rlayer,ADD_SELECTION_MASK)
gimp.pdb.gimp_layer_add_mask(rlayer,rmask) # Add layer mask
gimp.pdb.gimp_drawable_fill(rmask,FOREGROUND_FILL)
gimp.pdb.gimp_selection_none(stitch.cimage)
gimp.pdb.gimp_rect_select(stitch.cimage,rx0,ry0,rxsize,rysize,CHANNEL_OP_REPLACE,0,0.0)
gimp.pdb.gimp_edit_bucket_fill(rmask,
BG_BUCKET_FILL, # fill mode
NORMAL_MODE, # paint mode
100.0, # opacity
0.0, # threshhold
0, # sample merged
0.0, # x if no selection
0.0) # y if no selection
gimp.pdb.gimp_selection_none(stitch.cimage)
gimp.pdb.gimp_context_set_foreground(foreground)
gimp.pdb.gimp_context_set_background(background)
# Add the transformed selection to cimage with a mask
tlayer = gimp.pdb.gimp_layer_new(stitch.cimage, # image
xsize, # width
ysize, # height
RGB, # type
'transformed', # name
100, # opacity
NORMAL_MODE # layer combination mode
)
gimp.pdb.gimp_image_add_layer(stitch.cimage,tlayer,-1) # make new layer
foreground = gimp.pdb.gimp_context_get_foreground()
background = gimp.pdb.gimp_context_get_background()
gimp.pdb.gimp_context_set_foreground((0,0,0))
gimp.pdb.gimp_context_set_background((255,255,255))
gimp.pdb.gimp_drawable_fill(tlayer,FOREGROUND_FILL) # erase
gimp.pdb.gimp_edit_copy(stitch.timglayer) # copy selection
gimp.pdb.gimp_selection_none(stitch.cimage)
gimp.pdb.gimp_rect_select(stitch.cimage,tx0,ty0,txsize,tysize,CHANNEL_OP_REPLACE,0,0.0)
gimp.pdb.gimp_floating_sel_anchor(gimp.pdb.gimp_edit_paste(tlayer,0)) # paste and anchor
gimp.pdb.gimp_selection_none(stitch.cimage)
gimp.pdb.gimp_layer_add_alpha(tlayer) # Add alpha channel
tmask = gimp.pdb.gimp_layer_create_mask(tlayer,ADD_SELECTION_MASK)
gimp.pdb.gimp_layer_add_mask(tlayer,tmask) # Add layer mask
gimp.pdb.gimp_drawable_fill(tmask,FOREGROUND_FILL)
gimp.pdb.gimp_selection_none(stitch.cimage)
gimp.pdb.gimp_rect_select(stitch.cimage,tx0,ty0,txsize,tysize,CHANNEL_OP_REPLACE,0,0.0)
gimp.pdb.gimp_edit_bucket_fill(tmask,
BG_BUCKET_FILL, # fill mode
NORMAL_MODE, # paint mode
100.0, # opacity
0.0, # threshhold
0, # sample merged
0.0, # x if no selection
0.0) # y if no selection
gimp.pdb.gimp_selection_none(stitch.cimage)
gimp.pdb.gimp_context_set_foreground(foreground)
gimp.pdb.gimp_context_set_background(background)
rpixels = rlayer.get_pixel_rgn(0,0, # x,y
xsize, ysize, # width,height
TRUE, # changes applied to layer
FALSE) # Shadow
tpixels = tlayer.get_pixel_rgn(0,0, # x,y
xsize, ysize, # width,height
TRUE, # changes applied to layer
FALSE) # Shadow
rmpixels = rmask.get_pixel_rgn(0,0, # x,y
xsize, ysize, # width,height
TRUE, # changes applied to layer
FALSE) # Shadow
tmpixels = tmask.get_pixel_rgn(0,0, # x,y
xsize, ysize, # width,height
TRUE, # changes applied to layer
FALSE) # Shadow
for i in range (xsize):
for j in range(ysize):
# set the alpha channel for the layers
r,g,b,a = struct.unpack('B'*rpixels.bpp,rpixels[i,j])
m = struct.unpack('B'*rmpixels.bpp,rmpixels[i,j])
rpixels[i,j] = struct.pack('B'*rpixels.bpp,r,g,b,m[0])
r,g,b,a = struct.unpack('B'*tpixels.bpp,tpixels[i,j])
m = struct.unpack('B'*tmpixels.bpp,tmpixels[i,j])
tpixels[i,j] = struct.pack('B'*tpixels.bpp,r,g,b,m[0])
tsave = tpixels[0:xsize,0:ysize] # store the data for restoration later.
##if __debug__:
## rtestcorr = compute_correlation(rpixels,rpixels)
## ttestcorr = compute_correlation(tpixels,tpixels)
## print 'Test corr should be 1.0: ',rtestcorr,ttestcorr
correlation = compute_correlation(rpixels,tpixels)
##if __debug__:
## print 'Correlation is ',correlation
## #display = gimp.pdb.gimp_display_new(stitch.cimage)
## #widget=MessageWidget('Debug: press ok to continue.')
## #widget.main()
## #gimp.pdb.gimp_display_delete(display)
# adjust the control point using the correlation, if requested
xshift = 0.
yshift = 0.
rotate = 0.
scalxy = 1.
if stitch.cpcorrelate:
# Update the control point by maximizing the correlation
if stitch.npoints >= 1:
# get the approximate rotation and scale
rarray,tarray = stitch.arrays()
ttrans = compute_transform_matrix(rarray,tarray,stitch)
(sscale,srotation) = transform2rs(ttrans)
## if __debug__:
## print 'srotation is ',srotation, \
## math.atan2(-ttrans[0][1],ttrans[0][0],), \
## math.atan2(+ttrans[1][0],ttrans[1][1])
else:
srotation = 0.0
sscale = 1.0
xs = 0.0
ys = 0.0
rs = -srotation
ss = sscale
var = [xs,ys,rs,ss]
data = (tlayer,
rpixels,tpixels,
tsave,
xsize,ysize,
stitch.progressbar)
scale = [xscale,yscale,0.10,0.10]
itmax = 100
##if __debug__: print 'Initial scale,rotation ',ss,rs
# Optimizing functions should always be repeated just in
# case the the algorithm got stuck. If it did not get stuck,
# then the second call will be quick.
for iamoeba in range(2):
(varbest,correlation,iterations) = amoeba(var,
scale,
transform_correlation_func,
ftolerance=1.e-3,
xtolerance=1.e-3,
itmax=itmax,
data=data)
var = varbest
#if __debug__:
# print 'Best corr after ', iterations, ' iterations: ',correlation
(xshift,yshift,rotate,scalxy) = varbest
#if __debug__:
# print 'Final corr,xs,ys,rs,ss: ',correlation,xshift,yshift,rotate,scalxy,iterations
update_progress_bar(stitch.progressbar,'Correlating ...',1.0)
stitch.cimage.remove_layer(rlayer)
stitch.cimage.remove_layer(tlayer)
rx = (reference_selection[1]+reference_selection[3])/2.0
ry = (reference_selection[2]+reference_selection[4])/2.0
tx = (transformed_selection[1]+transformed_selection[3])/2.0
ty = (transformed_selection[2]+transformed_selection[4])/2.0
# inverse transform takes transformed center back to reference center
transform = matrix_invert(rss2transform(xshift,yshift,rotate,scalxy,xsize,ysize))
##if __debug__:
## print 'Test the CP calculation...'
## print 'This should be the identity matrix:'
## print matrixmultiply(transform,rss2transform(xshift,yshift,rotate,scalxy,xsize,ysize))
# since the images are centered in cimage,
# tx,ty in the big image corresponds to xcenter,ycenter in cimage.
xcenter = (xsize-1.0)/2.0
ycenter = (ysize-1.0)/2.0
stx,sty = xytransform(transform,xcenter,ycenter)
##if __debug__: print 'stx,sty:',stx,sty,tx+stx-xcenter,ty+sty-ycenter
stx = stx - xcenter
sty = sty - ycenter
update_progress_bar(stitch.progressbar,' ',0.0)
return control_point(rx,ry,tx+stx,ty+sty,correlation,colorbalance)
def rss2transform(xs,ys,rs,ss,xsize,ysize):
'''Convert rotation, shift and scale to a transform matrix.'''
# the rotation&scale should be around the center, not the corner
xs2 = (xsize-1)/2.0
ys2 = (ysize-1)/2.0
half_shift_minus = [[ 1.0, 0.0, 0.0],
[ 0.0, 1.0, 0.0],
[-xs2,-ys2, 1.0]]
half_shift_plus = [[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[xs2, ys2, 1.0]]
rotation = [[+math.cos(rs),+math.sin(rs), 0.0],
[-math.sin(rs),+math.cos(rs), 0.0],
[0.0, 0.0, 1.0]]
rotation = matrixmultiply(rotation,half_shift_plus)
rotation = matrixmultiply(half_shift_minus,rotation)
scale = [[ss, 0.0,0.0],
[0.0,ss, 0.0],
[0.0,0.0,1.0]]
scale = matrixmultiply(scale,half_shift_plus)
scale = matrixmultiply(half_shift_minus,scale)
shift = [[1.0 ,0.0, 0.0],
[0.0, 1.0, 0.0],
[xs, ys, 1.0]]
# put it all together
transform = matrixmultiply(scale,rotation)
transform = matrixmultiply(shift,transform)
return transform
def transform2rs(transform):
'''Compute rotation and scale from the tranform matrix.'''
# this is approximate since the shear would also come into
# the transform here.
srotation = (math.atan2(-transform[0][1],transform[0][0]) +
math.atan2(+transform[1][0],transform[1][1]))/2.0
# use the inverse rotation matrix to remove the rotation part
# of the transform. What's left should be the scaling.
rinv = [[+math.cos(srotation),-math.sin(srotation)],
[+math.sin(srotation),+math.cos(srotation)]]
smat = matrixmultiply(rinv,[[transform[0][0],transform[1][0]],
[transform[0][1],transform[1][1]]])
sscale = abs(smat[0][0]+smat[1][1])/2.0
sscale = sscale/transform[2][2] # apply overall scale
##if __debug__: print sscale,srotation
return (sscale,srotation)
def transform_correlation_func(var,data):
(xs,ys,rs,ss) = var
(tlayer,rpixels,tpixels,tsave,xsize,ysize,pbar) = data
corr = transform_correlation(tlayer,
rpixels,tpixels,
tsave,
xsize,ysize,
xs,ys,rs,ss)
update_progress_bar(pbar,'Correlating ...',max(corr,0.0,pbar.get_fraction()))
##if __debug__: print 'xs,ys,rs,ss,corr',xs,ys,rs,ss,corr
return corr
def transform_correlation(tlayer,
rpixels,tpixels,
tsave,
xsize,ysize,
xs,ys,rs,ss):
transform = rss2transform(xs,ys,rs,ss,xsize,ysize)
gimp.pdb.gimp_drawable_transform_matrix(tlayer,
transform[0][0],transform[1][0],transform[2][0],
transform[0][1],transform[1][1],transform[2][1],
transform[0][2],transform[1][2],transform[2][2],
TRANSFORM_FORWARD, # direction
INTERPOLATION_CUBIC, # interpolation
1, # supersample
5, # recursion level
1) # clip
tlayer.flush()
corr = compute_correlation(rpixels,tpixels) # compute correlation for this transform
tpixels[0:xsize,0:ysize] = tsave # restore layer to original
tlayer.flush()
return corr
def compute_correlation(rpixels,tpixels):
'''Compute the cross correlation between to pixel regions.'''
rformat = 'B'*rpixels.bpp # replicate 'B' by number of bytes
tformat = 'B'*tpixels.bpp
assert rpixels.w == tpixels.w
assert rpixels.h == tpixels.h
assert rpixels.bpp == 4
assert tpixels.bpp == 4
rmean = 0L
tmean = 0L
npix = 0L
# set up empty arrays to store the brightness etc. I assume this
# is faster than accessing and unpacking the pixel regions repeatedly.
rbrightness = [0]*rpixels.h
tbrightness = [0]*rpixels.h
ralpha = [0]*rpixels.h
talpha = [0]*rpixels.h
for j in range(rpixels.h):
rbrightness[j] = [0]*rpixels.w # set up empty arrays on the fly
tbrightness[j] = [0]*rpixels.w
ralpha[j] = [0]*rpixels.w
talpha[j] = [0]*rpixels.w
for i in range(rpixels.w):
rr,rg,rb,ra = struct.unpack(rformat,rpixels[i,j])
tr,tg,tb,ta = struct.unpack(tformat,tpixels[i,j])
rbrightness[j][i] = int(rr)+int(rg)+int(rb)
tbrightness[j][i] = int(tr)+int(tg)+int(tb)
ralpha[j][i] = int(ra)
talpha[j][i] = int(ta)
if int(ra) and int(ta):
rmean += long(rbrightness[j][i])
tmean += long(tbrightness[j][i])
npix = npix + 1L
rsum2 = 0.0
tsum2 = 0.0
rtsum = 0.0
correlation = 0.0
if npix:
rmean = float(rmean) / float(npix)
tmean = float(tmean) / float(npix)
for i in range(rpixels.w):
for j in range(rpixels.h):
if ralpha[j][i] and talpha[j][i]:
rval = float(rbrightness[j][i])-rmean
tval = float(tbrightness[j][i])-tmean
rtsum += rval*tval
rsum2 += rval*rval
tsum2 += tval*tval
if rsum2 and tsum2:
correlation = rtsum/(math.sqrt(rsum2)*math.sqrt(tsum2))
return correlation
def get_pickle_name(timage):
return 'stitch_'+timage.name+'-'+str(timage.ID)
def get_control_points_from_parasite(rimage,timage):
'''Check for and get a list of control points from reference image parasite.'''
# check the reference image for a parasite named after the transfomed
# image. Thus, there is a unique parasite for the pair of images.
name = get_pickle_name(timage)
parasite = rimage.parasite_find(name)
if parasite:
return pickle.loads(parasite.data)
else:
return None
def save_control_points_to_parasite(stitchobj):
'''Save the control point list to a reference image parasite.'''
# save the parasite in the reference image named after the transformed
# image so that there is a unique parasite name for the pair of images.
# Also save the inverse set of control points to the transformed image
# in case the user wants to apply the images the other way around.
if stitchobj.control_points:
cp_pickle = pickle.dumps(stitchobj.control_points)
name = get_pickle_name(stitchobj.timage)
stitchobj.rimage.attach_new_parasite(name,3,cp_pickle)
cp_pickle = pickle.dumps(stitchobj.inverse_control_points())
name = get_pickle_name(stitchobj.rimage)
stitchobj.timage.attach_new_parasite(name,3,cp_pickle)
def compute_transform_matrix(rarray,tarray,stitch=None):
'''Calculate the transformation matrix which defines how the transformed
image will be warped onto the reference image.'''
#if not stitch.npoints or stitch.npoints==0: return None
##if __debug__: print 'This is compute_transform_matrix'
#rarray,tarray = stitch.arrays()
npoints = len(rarray)
assert npoints == len(tarray),'rarray and tarray must be the same size.'
if npoints == 1:
# With one control point, just shift them on top of each other.
##if __debug__: print 'npoints is 1.'
xshift = rarray[0][0]-tarray[0][0]
yshift = rarray[0][1]-tarray[0][1]
transform = [[1.0,0.0,0.0],
[0.0,1.0,0.0],
[xshift,yshift,1.0]]
elif npoints == 2:
# With two control points, first shift the averages to the
# same place, then scale the length to the same value and
# finally rotate the segments to the same orientation.
##if __debug__: print 'npoints is 2.'
rxavg = (rarray[0][0] + rarray[1][0])/2.0
txavg = (tarray[0][0] + tarray[1][0])/2.0
ryavg = (rarray[0][1] + rarray[1][1])/2.0
tyavg = (tarray[0][1] + tarray[1][1])/2.0
xshift = rxavg - txavg
yshift = ryavg - tyavg
rdist = math.sqrt((rarray[0][0] - rarray[1][0])**2 + (rarray[0][1] - rarray[1][1])**2)
tdist = math.sqrt((tarray[0][0] - tarray[1][0])**2 + (tarray[0][1] - tarray[1][1])**2)
if rdist == 0.0 or tdist ==0.0: scale = 1.0
else: scale = tdist/rdist
rangle = math.atan2(rarray[0][1] - rarray[1][1],rarray[0][0] - rarray[1][0])
tangle = math.atan2(tarray[0][1] - tarray[1][1],tarray[0][0] - tarray[1][0])
angle = rangle - tangle
# The rotation and scale should be about the average
minus = [[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[-txavg, -tyavg, 1.0]]
plus = [[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[txavg, tyavg, 1.0]]
mrotation = [[+math.cos(angle),+math.sin(angle), 0.0],
[-math.sin(angle),+math.cos(angle), 0.0],
[0.0 ,0.0 , 1.0]]
mscale = [[1./scale, 0.0, 0.0],
[0.0, 1./scale, 0.0],
[0.0,0.0,1.0]]
mshift = [[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[xshift, yshift, 1.0]]
mrotation = matrixmultiply(minus,matrixmultiply(mrotation,plus))
mscale = matrixmultiply(minus,matrixmultiply(mscale,plus))
transform = matrixmultiply(mscale,matrixmultiply(mrotation,mshift))
else: # number of control points is 3 or more
# for the general case of 3 or more, use SVD to get a least squares
# fit to the transformation.
##if __debug__: print 'npoints is 3 or more.'
u,w,v = svd(tarray)
ut = transpose(u)
n = len(w)
maxw = max(w)
minw = maxw / 1.e10 # is this the right threshhold?
wi = []
wsmall = maxw
for i in range(n):
wi.append([0.0]*n)
if w[i] > minw:
wi[i][i] = 1.0/w[i]
if w[i] < wsmall: wsmall=w[i]
if wsmall and stitch: stitch.condition_number = maxw/wsmall
b = copy.deepcopy(rarray)
bu = matrixmultiply(ut,b)
buw = matrixmultiply(wi,bu)
buwv = matrixmultiply(v,buw)
transform = buwv
##if __debug__:
## print transform
return list(transform)
def matrix_invert(array):
'''Use SVD to do a matrix inversion.'''
u,w,v = svd(array)