-
Notifications
You must be signed in to change notification settings - Fork 2
/
mm_tool_imagemagick.py
1680 lines (1193 loc) · 51.4 KB
/
mm_tool_imagemagick.py
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
'''
mm_tool_imagemagick.py
ImageMagick functionality with GIMP
Author:
Michael Munzert (mail mm-log com)
Modified and extended:
Stephen Geary ( sjgcit gmail com )
JLLC is José Luis Lara Carrascal
Version: $Id: mm_tool_imagemagick.py,v 1.198 2015/11/17 22:59:14 sjg Exp $
2015.11.17 JLLC - Correct typo is temp var name
- Correct out of date developer email info
2014.02.25 SJG - Add Colorspace conversion routines
2014.02.22 SJG - Modify the way scipy and numpy are imported
This make sure the rest of the plugin is registered
and only the parts that require scipy will not be
registered.
2014.02.21 SJG - Fix an issue with the way popen() works on MS Windows
You have to explicitly state the stdin channel must
be redirected to PIPE or popen() can fail.
2014.02.20 SJG - Add checks on getstrokes() return value is None
- Add lens distorion correction by path using Linear
and Quadratic models
- Add a kludge to command line o try and avoid a problem
on some MS Windows system
2014.02.19 SJG - Added config value for resize filter to retain last value
2014.02.17 SJG - Added support for mm_tool_imagemagick configuration file in gimp.directory
- Fixed bug in perspective tool related to use using vertical guides
- Changed ordering of undo group start and end until after avoidable error returns
- Changed handling of tempfile creation to avoid runtime errors
- Fixed bug in use creation of tempimage ( was using layer[0] not tempdrawable ) .
2014.02.16 SJG - Changes to simply registration code.
Addition of experimental lens correction tools using paths.
2014.02.12 SJG - Change rotation tool to automatically detect whether to use
vertical or horizontal as target.
2014.02.09 SJG - Add a plugin allow any mogrify command to be entered by the user
SJG - Add code to request resize filter list from ImageMagick ar runtime
SJG - Add support for resize filters with Perspective and Rotate tools
2014.02.08 SJG - Replace all backslashes in file paths with forward slashes on Windows
2014.02.04 SJG - Added rotation tool using path
SJG - Added color dot product tool
SJG - Added color distance tool
2014.02.03 SJG - Added perspective correction based on path
SJG - Changed MS Windows path and added some error handling
SJG - Added better undo support
SJG - Improved perspective tranformation
2014.02.02 SJG - Refactored code
SJG - Added 'sketch' plugin
SJG - Added 'charcoal' plugin
SJG - Added Sepia tone plugin
SJG - Allow update of plugin window during subprocess execution
SJG - Changed menu placement
2014.02.01 SJG - Added better control of source and destination image and layer
SJG - Changed Menu placement and name
SJG - Changed function name
2014.01.31 SJG - Added more filters
2010.02.03 MM - Added different filters.
modelled after the trace plugin (lloyd konneker, lkk, bootch at nc.rr.com)
License:
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.
The GNU Public License is available at
http://www.gnu.org/copyleft/gpl.html
'''
from gimpfu import *
import subprocess
import os
import sys
import time
import gtk
import math
import shutil
try:
import numpy
numpy_imported = True
try:
import scipy.optimize as scopt
scipy_imported = True
except:
scipy_imported = False
except ImportError:
numpy_imported = False
scipy_imported = False
#----------------------------------------------------------------------------------
def plugin_maketempfile( image, src ):
# Copy so the save operations doesn't affect the original
tempimage = pdb.gimp_image_duplicate( image )
if not tempimage:
print "mm_tool_imagemagick could not create temporary image file."
return None, None, None
# Use temp file names from gimp, it reflects the user's choices in gimp.rc
tempfilename = pdb.gimp_temp_name( "tif" )
if sys.platform.startswith( "win" ):
# on MS Windows we can use either forward- or back- slashes
# in file paths.
# Backslashes can be problematic when dealing with strings
# so let's replace them just in case.
tempfilename = tempfilename.replace( "\\", "/" )
if src == 0:
# Get the current visible
tempdrawable = pdb.gimp_layer_new_from_visible( image, tempimage, "visible" )
else:
# Save in temporary. Note: empty user entered file name
tempdrawable = pdb.gimp_image_get_active_drawable( tempimage )
# !!! Note no run-mode first parameter, and user entered filename is empty string
pdb.gimp_progress_set_text( "Saving a copy" )
pdb.gimp_file_save( tempimage, tempdrawable, tempfilename, "" )
return tempfilename, tempdrawable, tempimage
#----------------------------------------------------------------------------------
def plugin_saveresult( image, dest, tempfilename, tempimage ):
# Get image file name
name = image.filename
if dest == 0 :
# new image
try:
newimage = pdb.file_tiff_load( tempfilename, "" )
# Get exif data
exifdata = image.parasite_find( "exif-data" )
# Write exif data
if exifdata != None:
newimage.parasite_attach( exifdata )
# Write name
if name != None:
newimage.filename = name
gimp.Display( newimage )
except:
print "mm_tool_imagemagick could not load tmep file as new image."
elif dest == 1:
# Replace current layer
pos = pdb.gimp_image_get_item_position( image, image.active_layer )
try:
newlayer = pdb.gimp_file_load_layer( image, tempfilename )
image.remove_layer( image.active_layer )
image.add_layer( newlayer, pos )
except:
print "mm_tool_imagemagick Could not load temp file into existing layer."
elif dest == 2:
# Add as a new layer in the opened image
try:
newlayer = pdb.gimp_file_load_layer( image, tempfilename )
image.add_layer( newlayer,0 )
except:
print "mm_tool_imagemagick Could not load temp file into new layer."
# cleanup
plugin_tidyup( tempfilename )
# Note the new image is dirty in Gimp and the user will be asked to save before closing.
gimp.displays_flush()
gimp.delete( tempimage ) # delete the temporary image
#----------------------------------------------------------------------------------
def plugin_tidyup( fname ):
if os.access( fname, os.F_OK ):
os.remove( fname )
#----------------------------------------------------------------------------------
def plugin_docommand( function, arg, tempfilename, title ):
if sys.platform.startswith( "linux" ):
# Command line for linux
command = function + " " + arg + " \"" + tempfilename + "\""
elif sys.platform.startswith( "darwin" ):
# Command line for OSX
command = function + " " + arg + " \"" + tempfilename + "\""
elif sys.platform.startswith( "win" ):
# On WIndows we have to find the ImageMagick directory ourselves
dl = os.listdir( "C:/Program Files" )
cmdpath = None
for d in dl:
# ImageMagick installs to a folder starting with ImageMagick
# but with version information after that we cannot know
if d.startswith("ImageMagick"):
cmdpath = "\"C:/Program Files/" + d + "/" + function + ".exe\""
break
command = cmdpath + " " + arg + " \" -quiet " + tempfilename + "\""
else:
# did not pick up OS from sys.platform
gimp.message( "OS was not identified by script : " + sys.platform )
return False
# Invoke mogrify.
pdb.gimp_progress_set_text( title )
pdb.gimp_progress_pulse()
# NOTE : Sometimes pythonw.exe fails if you do not PIPE all three
# of the standard channels, even if your process does not need them.
# so we must use stdin as well as stdout and stderr
child = subprocess.Popen( command,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
shell=True
)
# child.communicate()
while child.poll() is None:
pdb.gimp_progress_pulse()
time.sleep(0.2)
# if child.returncode != 0:
stdoutdata, stderrdata = child.communicate()
# gimp.message( "Error return was [ " + stderrdata + "]" )
##__devcode
print "+----------------------------------------------------------+"
print stdoutdata
print "+----------------------------------------------------------+"
##__end_devcode
return True
#----------------------------------------------------------------------------------
# run a command which returns text but does no image processing
def plugin_silentcommand( function, arg ):
if sys.platform.startswith( "linux" ):
# Command line for linux
command = function + " " + arg
elif sys.platform.startswith( "darwin" ):
# Command line for OSX
command = function + " " + arg
elif sys.platform.startswith( "win" ):
# On WIndows we have to find the ImageMagick directory ourselves
dl = os.listdir( "C:/Program Files" )
cmdpath = None
for d in dl:
# ImageMagick installs to a folder starting with ImageMagick
# but with version information after that we cannot know
if d.startswith("ImageMagick"):
cmdpath = "\"C:/Program Files/" + d + "/" + function + ".exe\""
break
command = cmdpath + " " + arg
else:
# did not pick up OS from sys.platform
gimp.message( "OS was not identified by script : " + sys.platform )
return None
# NOTE : Sometimes pythonw.exe fails if you do not PIPE all three
# of the standard channels, even if your process does not need them.
# so we must use stdin as well as stdout and stderr
child = subprocess.Popen( command,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
shell=True
)
# child.communicate()
stdoutdata, stderrdata = child.communicate()
return stdoutdata
#----------------------------------------------------------------------------------
def plugin_resize_filters( idx ):
if not hasattr( plugin_resize_filters, "resize_filters"):
# initialize
filters = plugin_silentcommand( "mogrify", "-list filter" )
if filters != None:
plugin_resize_filters.resize_filters = filters.split("\n")
else:
# fallback in case we could not get the list from mogrify
plugin_resize_filters.resize_filters = [ "Lanczos",
"Catrom",
"Mitchell",
"Cubic",
"Point",
"Box",
"Triangle",
"Hermite",
"Gaussian",
"Quadratic",
"Blackman",
"Hanning",
"Kaiser",
"Hamming",
"Bartlett",
"Parzen",
"Welsh",
"Bohman"
]
if idx == -1:
return plugin_resize_filters.resize_filters
else:
f = plugin_resize_filters.resize_filters[idx]
plugin_setcfgtag( "default-filter", f )
return f
#----------------------------------------------------------------------------------
def plugin_color_spaces( idx ):
if not hasattr( plugin_color_spaces, "colorspaces"):
# initialize
cspaces = plugin_silentcommand( "mogrify", "-list colorspace" )
if cspaces != None:
plugin_color_spaces.colorspaces = cspaces.split("\n")
else:
# fallback in case we could not get the list from mogrify
plugin_color_spaces.colorspaces = [ "RGB", "HSV", "Lab" ]
if idx == -1:
return plugin_color_spaces.colorspaces
else:
f = plugin_color_spaces.colorspaces[idx]
return f
#----------------------------------------------------------------------------------
def getstrokes( image, numpointswanted ):
vectors = pdb.gimp_image_get_active_vectors(image)
nstrokes, strokes = pdb.gimp_vectors_get_strokes(vectors)
if nstrokes == 0:
# must be at least one stroke or we have no points
gimp.message( "No strokes found" )
return None
stoke_type, n_points, p, closed = pdb.gimp_vectors_stroke_get_points(vectors, strokes[0])
if n_points != 6*numpointswanted:
# Note that 2 (x,y) ordinate pairs becomes 6 values per ordinate pair
gimp.message( "Found " + str(n_points/6) + " points, need " + str(numpointswanted) )
return None
return p
#----------------------------------------------------------------------------------
def plugin_resize( image, drawable, size, filtertouse, src, dest ):
tempfilename, tempdrawable, tempimage = plugin_maketempfile( image, src )
if tempfilename == None:
return
width = tempdrawable.width
height = tempdrawable.height
arg = "-filter " + plugin_resize_filters( filtertouse )
if height > width:
arg = arg + " -resize x" + str(size) + " "
else :
arg = arg + " -resize " + str(size) + " "
plugin_setcfgtag( "default-resize", str(size) )
pdb.gimp_image_undo_group_start(image)
if plugin_docommand( "mogrify", arg, tempfilename, "Resizing" ) == True:
plugin_saveresult( image, dest, tempfilename, tempimage )
plugin_tidyup( tempfilename )
pdb.gimp_image_undo_group_end(image)
#----------------------------------------------------------------------------------
def plugin_sketch( image, drawable, radius, sigma, angle, src, dest ):
tempfilename, tempdrawable, tempimage = plugin_maketempfile( image, src )
if tempfilename == None:
return
arg = "-sketch " + str(radius) + "x" + str(sigma) + "+" + str(angle)
pdb.gimp_image_undo_group_start(image)
if plugin_docommand( "mogrify", arg, tempfilename, "Sketching" ) == True:
plugin_saveresult( image, dest, tempfilename, tempimage )
plugin_tidyup( tempfilename )
pdb.gimp_image_undo_group_end(image)
#----------------------------------------------------------------------------------
def plugin_charcoal( image, drawable, thickness, src, dest ):
tempfilename, tempdrawable, tempimage = plugin_maketempfile( image, src )
if tempfilename == None:
return
arg = "-charcoal " + str(thickness)
pdb.gimp_image_undo_group_start(image)
if plugin_docommand( "mogrify", arg, tempfilename, "Charcoal rendering" ) == True:
plugin_saveresult( image, dest, tempfilename, tempimage )
plugin_tidyup( tempfilename )
pdb.gimp_image_undo_group_end(image)
#----------------------------------------------------------------------------------
def plugin_sepia( image, drawable, threshold, src, dest ):
tempfilename, tempdrawable, tempimage = plugin_maketempfile( image, src )
if tempfilename == None:
return
arg = "-sepia-tone " + str(threshold) + "%"
pdb.gimp_image_undo_group_start(image)
if plugin_docommand( "mogrify", arg, tempfilename, "Sepia tone rendering" ) == True:
plugin_saveresult( image, dest, tempfilename, tempimage )
plugin_tidyup( tempfilename )
pdb.gimp_image_undo_group_end(image)
#----------------------------------------------------------------------------------
def plugin_perspective( image, drawable, force, filtertouse, src, dest ):
# get points for transform from image
p = getstrokes( image, 4 )
if p == None:
return
# if force flag is True then we map the points to the top and bottom of
# the time by projecting lines from the points we have. This will produce
# a perspective correction suitable for focing building verticals to be
# vertical in the final image ( assuming you choose points on the
# correct lines in the image ).
q = []
if force == True:
# map the points to the top and bottom of the image
w = drawable.width
h = drawable.height
# it's possible the lines could be vertical
# which will error when we divide by zero
if p[6] == p[0]:
q.append( p[0] )
q.append( 0 )
q.append( p[0] )
q.append( h-1 )
else:
a = ( p[7] - p[1] ) / ( p[6] - p[0] )
b = p[7] - ( a * p[6] )
q.append( -b/a )
q.append( 0 )
q.append( ( h-1-b ) / a )
q.append( h-1 )
if p[18] == p[12]:
q.append( p[18] )
q.append( 0 )
q.append( p[18] )
q.append( h-1 )
else:
a = ( p[19] - p[13] ) / ( p[18] - p[12] )
b = p[19] - ( a * p[18] )
# note the code that follows expects the order to anti-clockwise
# so these are added in a different order
q.append( ( h-1-b ) / a )
q.append( h-1 )
q.append( -b/a )
q.append( 0 )
else:
# just use the points we're given
q.append( p[0] )
q.append( p[1] )
q.append( p[6] )
q.append( p[7] )
q.append( p[12] )
q.append( p[13] )
q.append( p[18] )
q.append( p[19] )
# need to work out the box to map to
# we do this by using the middle two x and y ordinates of the
# given points. We map to this.
# routine assume points were entered from top-left quadrant anti-clockwise
xa = sorted( [ q[0], q[2], q[4], q[6] ] )
ya = sorted( [ q[1], q[3], q[5], q[7] ] )
# do the transformation
tempfilename, tempdrawable, tempimage = plugin_maketempfile( image, src )
if tempfilename == None:
return
arg = "-matte -virtual-pixel transparent -filter " + plugin_resize_filters( filtertouse ) + " -distort Perspective \""
arg = arg + str(q[0]) + "," + str(q[1]) + " " + str(xa[1]) + "," + str(ya[1]) + " "
arg = arg + str(q[2]) + "," + str(q[3]) + " " + str(xa[1]) + "," + str(ya[2]) + " "
arg = arg + str(q[4]) + "," + str(q[5]) + " " + str(xa[2]) + "," + str(ya[2]) + " "
arg = arg + str(q[6]) + "," + str(q[7]) + " " + str(xa[2]) + "," + str(ya[1]) + " "
arg = arg + "\""
pdb.gimp_image_undo_group_start(image)
if plugin_docommand( "mogrify", arg, tempfilename, "Perspective Transform" ) == True:
plugin_saveresult( image, dest, tempfilename, tempimage )
plugin_tidyup( tempfilename )
pdb.gimp_image_undo_group_end(image)
#----------------------------------------------------------------------------------
def plugin_rotate( image, drawable, filtertouse , src, dest ):
# get points for transform from image
p = getstrokes(image,2)
if p == None:
return
# calculate angle
# note that y ordinates are opposite from what you expect
# in maths, as the top is zero and the bottom is positive
y7 = image.height - 1 - p[7]
y1 = image.height - 1 - p[1]
if p[6] > p[0]:
angle0 = math.atan2( y7-y1, p[6]-p[0] )
else:
angle0 = math.atan2( y1-y7, p[0]-p[6] )
angle0 = 180.0 * angle0 / math.pi
if angle0 > 0 :
if angle0 > 45:
angle = angle0 - 90
else:
angle = angle0
else:
absangle = math.fabs( angle0 )
if absangle > 45:
angle = 90 - absangle
else:
angle = angle0
# do the transformation
tempfilename, tempdrawable, tempimage = plugin_maketempfile( image, src )
if tempfilename == None:
return
arg = "-matte -virtual-pixel transparent -filter " + plugin_resize_filters( filtertouse ) + " +distort SRT \"" + str(angle) + "\" "
pdb.gimp_image_undo_group_start(image)
if plugin_docommand( "mogrify", arg, tempfilename, "Rotation" ) == True:
plugin_saveresult( image, dest, tempfilename, tempimage )
plugin_tidyup( tempfilename )
pdb.gimp_image_undo_group_end(image)
#----------------------------------------------------------------------------------
##__devcode
def plugin_lenscorrection( image, drawable, filtertouse , src, dest ):
# get points for transform from image
p = getstrokes(image,5)
if p == None:
return
# Note that radi are normalized (!)
cx = image.width / 2.0
cy = image.height / 2.0
norm = cx
if cy < norm:
norm = cy
g = ( cx, cy, norm )
R0, s0, c0 = lc_rsc( p, 0, g )
R1, s1, c1 = lc_rsc( p, 1, g )
R2, s2, c2 = lc_rsc( p, 2, g )
R3, s3, c3 = lc_rsc( p, 3, g )
R4, s4, c4 = lc_rsc( p, 4, g )
print R0, R1, R2, R3, R4
# solve the equation
#
# We wish to obtain values for the tansform R = r*( A*r*r*r + B*r*r + C*r*r + D )
#
# From logical considerations we get :
#
# B = F*F + E*E - 2 - 2*A
# C = 3 + A - F*F - 2*E*E
# D = E*E
#
# And we fit to that equation
# initial estimate for line we map to
p0 = ( R4*s4 - R0*s0 ) / ( R4*c4 - R0*c0 )
q0 = R0*s0 - p0*R0*c0
# Note the guess values refer to A,E,F,p,q in that order
#
guess = [ 0, 1, 1, p0, q0 ]
# print guess
t = [ R0,s0,c0, R1,s1,c1, R2,s2,c2, R3,s3,c3, R4,s4,c4 ]
# V, covx, info, ier, msg = scopt.leastsq( lc_fn2, guess, t, full_output=True )
V, info, ier, msg = scopt.fsolve( lc_fn2, guess, t, full_output=True )
D = V[1]*V[1]
A = V[0]
B = V[2]*V[2] + D - 2 - 2*A
C = 1 - A - B - D
print "co-effs = ", A, B, C, D
print info['fvec']
print info['nfev']
# C now contains the values we need for the ImageMagick barrel distortion correction
# do the transformation
tempfilename, tempdrawable, tempimage = plugin_maketempfile( image, src )
if tempfilename == None:
return
arg = "-matte -virtual-pixel transparent -filter " + plugin_resize_filters( filtertouse ) + " -distort Barrel"
arg = arg + " \""+ str(A) + " " + str(B) + " " + str(C) + " " + str(D) + "\" "
pdb.gimp_image_undo_group_start(image)
if plugin_docommand( "mogrify", arg, tempfilename, "Barrel" ) == True:
plugin_saveresult( image, dest, tempfilename, tempimage )
plugin_tidyup( tempfilename )
pdb.gimp_image_undo_group_end(image)
print msg
#--------------------------
def lc_fn( V, RSC ):
( A, G1, H1, p, q ) = V
( R0,s0,c0, R1,s1,c1, R2,s2,c2, R3,s3,c3, R4,s4,c4 ) = RSC
B = G1*G1-2-2*A
C = 3-A-H1*H1
eq0 = A*( (q/(s0-p*c0))**4 ) + B*( (q/(s0-p*c0))**3 ) + C*( (q/(s0-p*c0))**2 ) + ( 1-(A+B+C) )*q/(s0-p*c0) - R0
eq1 = A*( (q/(s1-p*c1))**4 ) + B*( (q/(s1-p*c1))**3 ) + C*( (q/(s1-p*c1))**2 ) + ( 1-(A+B+C) )*q/(s1-p*c1) - R1
eq2 = A*( (q/(s2-p*c2))**4 ) + B*( (q/(s2-p*c2))**3 ) + C*( (q/(s2-p*c2))**2 ) + ( 1-(A+B+C) )*q/(s2-p*c2) - R2
eq3 = A*( (q/(s3-p*c3))**4 ) + B*( (q/(s3-p*c3))**3 ) + C*( (q/(s3-p*c3))**2 ) + ( 1-(A+B+C) )*q/(s3-p*c3) - R3
eq4 = A*( (q/(s4-p*c4))**4 ) + B*( (q/(s4-p*c4))**3 ) + C*( (q/(s4-p*c4))**2 ) + ( 1-(A+B+C) )*q/(s4-p*c4) - R4
'''
eq0 = A*(q**4) + B*(q**3)*(s0-p*c0) + C*(q**2)*((s0-p*c0)**2) + (1-(A+B+C))*q*((s0-p*c0)**3) - R0*((s0-p*c0)**4)
eq1 = A*(q**4) + B*(q**3)*(s1-p*c1) + C*(q**2)*((s1-p*c1)**2) + (1-(A+B+C))*q*((s1-p*c1)**3) - R1*((s1-p*c1)**4)
eq2 = A*(q**4) + B*(q**3)*(s2-p*c2) + C*(q**2)*((s2-p*c2)**2) + (1-(A+B+C))*q*((s2-p*c2)**3) - R2*((s2-p*c2)**4)
eq3 = A*(q**4) + B*(q**3)*(s3-p*c3) + C*(q**2)*((s3-p*c3)**2) + (1-(A+B+C))*q*((s3-p*c3)**3) - R3*((s3-p*c3)**4)
eq4 = A*(q**4) + B*(q**3)*(s4-p*c4) + C*(q**2)*((s4-p*c4)**2) + (1-(A+B+C))*q*((s4-p*c4)**3) - R4*((s4-p*c4)**4)
'''
return [ eq0, eq1, eq2, eq3, eq4 ]
#--------------------------
def lc_fn2( V, RSC ):
( A, E, F, p, q ) = V
( R0,s0,c0, R1,s1,c1, R2,s2,c2, R3,s3,c3, R4,s4,c4 ) = RSC
D = E*E
B = F*F + D - 2 - 2*A
C = 1 - A - B - D
r = q/(s0-p*c0)
eq0 = A*( r**4 ) + B*( r**3 ) + C*( r**2 ) + D*r - R0
r = q/(s1-p*c1)
eq1 = A*( r**4 ) + B*( r**3 ) + C*( r**2 ) + D*r - R1
r = q/(s2-p*c2)
eq2 = A*( r**4 ) + B*( r**3 ) + C*( r**2 ) + D*r - R2
r = q/(s3-p*c3)
eq3 = A*( r**4 ) + B*( r**3 ) + C*( r**2 ) + D*r - R3
r = q/(s4-p*c4)
eq4 = A*( r**4 ) + B*( r**3 ) + C*( r**2 ) + D*r - R4
return [ eq0, eq1, eq2, eq3, eq4 ]
##__end_devcode
#--------------------------
def plugin_lc_b( image, drawable, filtertouse , src, dest ):
'''
Try to correct lens distortion my matching three points
on a curve to R = r*( (1-E+E)*r*r + E*E )
'''
# get points for transform from image
p = getstrokes(image,3)
if p == None:
return
# Note that radi are normalized (!)
cx = image.width / 2.0
cy = image.height / 2.0
norm = cx
if cy < norm:
norm = cy
g = ( cx, cy, norm )
R0, s0, c0 = lc_rsc( p, 0, g )
R1, s1, c1 = lc_rsc( p, 1, g )
R2, s2, c2 = lc_rsc( p, 2, g )
# solve the equation
# initial estimate for solution
p0 = ( R2*s2 - R0*s0 ) / ( R2*c2 - R0*c0 )
q0 = R0*s0 - p0*R0*c0
guess = [ 0.0 ,p0, q0 ]
t = [ R0,s0,c0, R1,s1,c1, R2,s2,c2 ]
V, info, ier, msg = scopt.fsolve( lc_fn_b, guess, t, full_output=True )
D = V[0]*V[0]
B = 1.0 - D
# C now contains the values we need for the ImageMagick barrel distortion correction
# do the transformation
tempfilename, tempdrawable, tempimage = plugin_maketempfile( image, src )
if tempfilename == None:
return
arg = "-matte -virtual-pixel transparent -filter " + plugin_resize_filters( filtertouse ) + " -distort Barrel"
arg = arg + " \"0.0 " + str(B) + " 0.0 " + str(D) + "\" "
pdb.gimp_image_undo_group_start(image)
if plugin_docommand( "mogrify", arg, tempfilename, "Barrel" ) == True:
plugin_saveresult( image, dest, tempfilename, tempimage )
plugin_tidyup( tempfilename )
pdb.gimp_image_undo_group_end(image)
#--------------------------
def lc_fn_b( V, RSC ):
( E, p, q ) = V
( R0,s0,c0, R1,s1,c1, R2,s2,c2 ) = RSC
D = E*E
# fitting R = r*( (1-E*E)*r*r + E*E )
r = q/(s0-p*c0)
eq0 = ( (1-D)*r*r + D )*r - R0
r = q/(s1-p*c1)
eq1 = ( (1-D)*r*r + D )*r - R1
r = q/(s2-p*c2)
eq2 = ( (1-D)*r*r + D )*r - R2
return [ eq0, eq1, eq2 ]
#--------------------------
def plugin_lc_c( image, drawable, filtertouse , src, dest ):
'''
Try to correct lens distorion by mapping three points
on a curve to a line.
Use the model : R = r*( C*r + 1 - C )
'''
# get points for transform from image
p = getstrokes(image,3)
if p == None:
return
# Note that radi are normalized (!)
cx = image.width / 2.0
cy = image.height / 2.0
norm = cx
if cy < norm:
norm = cy
g = ( cx, cy, norm )
R0, s0, c0 = lc_rsc( p, 0, g )
R1, s1, c1 = lc_rsc( p, 1, g )
R2, s2, c2 = lc_rsc( p, 2, g )
# solve the equation
# initial estimate for solution
p0 = ( R2*s2 - R0*s0 ) / ( R2*c2 - R0*c0 )
q0 = R0*s0 - p0*R0*c0
guess = [ 0.0 ,p0, q0 ]
t = [ R0,s0,c0, R1,s1,c1, R2,s2,c2 ]
C, info, ier, msg = scopt.fsolve( lc_fn_c, guess, t, full_output=True )
D = 1.0 - C[0]
# C now contains the values we need for the ImageMagick barrel distortion correction
# do the transformation
tempfilename, tempdrawable, tempimage = plugin_maketempfile( image, src )
if tempfilename == None:
return
arg = "-matte -virtual-pixel transparent -filter " + plugin_resize_filters( filtertouse ) + " -distort Barrel"
arg = arg + " \"0.0 0.0 " + str(C[0]) + " " + str(D) + "\" "
pdb.gimp_image_undo_group_start(image)
if plugin_docommand( "mogrify", arg, tempfilename, "Barrel" ) == True:
plugin_saveresult( image, dest, tempfilename, tempimage )
plugin_tidyup( tempfilename )
pdb.gimp_image_undo_group_end(image)
#--------------------------
def lc_fn_c( V, RSC ):
( C, p, q ) = V
( R0,s0,c0, R1,s1,c1, R2,s2,c2 ) = RSC
eq0 = C*(q**2) + (1-C)*q*(s0-p*c0) - R0*((s0-p*c0)**2)
eq1 = C*(q**2) + (1-C)*q*(s1-p*c1) - R1*((s1-p*c1)**2)
eq2 = C*(q**2) + (1-C)*q*(s2-p*c2) - R2*((s2-p*c2)**2)
return [ eq0, eq1, eq2 ]
#--------------------------
def lc_rsc( p, k, g ):
x = p[6*k] - g[0]
y = p[(6*k)+1] - g[1]
R = math.sqrt( x*x + y*y )
s = y / R
c = x / R
R = R / g[2]
return ( R, s, c )
#-----------------------------------
##__devcode
def plugin_lenscorrection_inverse( image, drawable, filtertouse , src, dest ):
# get points for transform from image
p = getstrokes(image,5)
if p == None:
return
# Note that radi are normalized (!)