-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCAIR.cpp
More file actions
executable file
·2158 lines (1858 loc) · 81.1 KB
/
CAIR.cpp
File metadata and controls
executable file
·2158 lines (1858 loc) · 81.1 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
//=========================================================================================================//
//CAIR - Content Aware Image Resizer
//Copyright (C) 2008 Joseph Auman (brain.recall@gmail.com)
//=========================================================================================================//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//This library 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
//Lesser General Public License for more details.
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//=========================================================================================================//
//This thing should hopefully perform the image resize method developed by Shai Avidan and Ariel Shamir.
//=========================================================================================================//
//TODO (maybe):
// - Add an Energy_Middle() function to allow more than two energy map threads.
// - Try doing Poisson image reconstruction instead of the averaging technique in CAIR_HD() if I can figure it out (see the ReadMe).
// - Abstract out pthreads into macros allowing for multiple thread types to be used (ugh, not for a while at least)
// - Maybe someday push CAIR into OO land and create a class out of it (pff, OO is the devil!).
//=========================================================================================================//
//KNOWN BUGS:
// - The threading changes in v2.16 lost the reentrant capability of CAIR. (If this hits someone hard, let me know.)
// - The percent of completion for the CAIR_callback in CAIR_HD and CAIR_Removal are often wrong.
//=========================================================================================================//
//CHANGELOG:
//CAIR v2.17 Changelog:
// - Ditched vectors for dynamic arrays, for about a 15% performance boost.
// - Added some headers into CAIR_CML.h to fix some compilier errors with new versions of g++. (Special thanks to Alexandre Prokoudine)
// - Added CAIR_Threads(), which allows the ability to dynamically change the number of threads CAIR will use.
// NOTE: Don't ever call CAIR_Threads() while CAIR() is processing an image, unless you're a masochist.
// - Added CAIR_callback parameters to CAIR(), CAIR_Removal(), and CAIR_HD(). This function pointer will be called every cycle,
// passing the function the percent complete (0 to 1). If the function returns false, then the resize is canceled.
// Then, CAIR(), CAIR_Removal(), and CAIR_HD() would also return a false, leaving the destination image/weights in an unknown state.
// Set to NULL if this does not need to be used.
//CAIR v2.16 Changelog:
// - A long overdue overhaul of the threading system yielded about a 40% performance boost. All threads, semaphores, and mutexes are kept around for
// as long as possible, instead of destroying them every step.
// - I stumbled across a bug in CAIR_Add() where some parts of the artifical weight matrix weren't being updated, creating slightly incorrect images.
// - Comment overhauls to reflect the new threading.
//CAIR v2.15.1 Changelog:
// - Mutexes and conditions used in Energy_Map() are now properly destroyed, fixing a serious memory leak. This was discovered when
// processing huge images (7500x3800) that would cause the process to exceed the 32-bit address space.
// Special thanks to Klaus Nordby for hitting this bug. CAIR has now been tested up to 9800x7800 without issue.
// - A potential memory leak in Deallocate_Matrix() in the CML was squashed.
// - By default CAIR now uses 4 threads (yay quad-core!).
//CAIR v2.15 Changelog:
// - Added the new forward energy algorithm. A new CAIR_energy parameter determines the type of energy function to use. Forward energy
// produces less artifacts in most images, but comes at a 5% performance cost. Thanks to Matt Newel for pointing it out.
// Read the paper on it here: http://www.faculty.idc.ac.il/arik/papers/vidRet.pdf
// - The number of threads CAIR uses can now be set by CAIR_NUM_THREADS. This currently does not apply to the Energy calculations.
// On my dual-core system, I netted a 5% performance boost by reducing thread count from 4 to 2.
// - Separate destination weights for the resize to standardize the interface.
// - Removed "namespace std" from source headers. Special thanks to David Oster.
// - Removed the clipping Get() method from the CML. This makes the CML generic again.
// - Comment clean-ups.
// - Comments have been spell-checked. Apparently, I don’t speel so good. (thanks again to David Oster)
//CAIR v2.14 Changelog:
// - CAIR has been relicensed under the LGPLv2.1
//CAIR v2.13 Changelog:
// - Added CAIR_Image_Map() and CAIR_Map_Resize() to allow for "content-aware multi-size images." Now it just needs to get put into a
// file-format.
// - CAIR() and CAIR_HD() now properly copy the Source to Dest when no resize is done.
// - Fixed a bug in CAIR_HD(), Energy/TEnergy confusion.
// - Fixed a compiler warning in main().
// - Changed in Remove_Quadrant() "pixel remove" into "int remove"
// - Comment updates and I decided to bring back the tabs (not sure why I got rid of them).
//CAIR v2.12 Changelog:
// - About 20% faster across the board.
// - Unchanged portions of the energy map are now retained. Special thanks to Jib for that (remind me to ask him how it works :-) ).
// - Add_Edge() and Remove_Edge() now update the Edge in UNSAFE mode when able.
// - The CML now has a CML_DEBUG mode to let the developers know when they screwed up.
// - main() now displays the runtime with three decimal places for better accuracy. Special thanks to Jib.
// - Various comment updates.
//CAIR v2.11 Changelog: (The Super-Speedy Jib version)
// - 40% speed boost across the board with "high quality"
// - Remove_Path() and Add_Path() directly recalculate only changed edge values. This gives the speed of low quality while
// maintaining high quality output. Because of this, the quality factor is no longer used and has been removed. (Special thanks to Jib)
// - Grayscale values during a resize are now properly recalculated for better accuracy.
// - main() has undergone a major overhaul. Now most operations are accessible from the CLI. (Special thanks to Jib)
// - Now uses multiple edge detectors, with V_SQUARE offering some of the best quality. (Special thanks to Jib)
// - Minor change to Grayscale_Pixel() to increase speed. (Special thanks to Jib)
//CAIR v2.10 Changelog: (The great title of v3.0 is when I have CAIR_HD() using Poisson reconstruction, a ways away...)
// - Removed multiple levels of derefrencing in all the thread functions for a 15% speed boost across the board.
// - Changed the way CAIR_Removal() works for more flexibility and better operation.
// - Fixed a bug in CAIR_Removal(): infinite loop problem that got eliminated with its new operation
// - Some comment updates.
//CAIR v2.9 Changelog:
// - Row-majorized and multi-threaded Add_Weights(), which gave a 40% speed boost while enlarging.
// - Row-majorized Edge_Detect() (among many other functions) which gave about a 10% speed boost with quality == 1.
// - Changed CML_Matrix::Resize_Width() so it gracefully handles enlarging beyond the Reserve()'ed max.
// - Changed Energy_Path() to return a long instead of int, just in case.
// - Fixed an enlarging bug in CAIR_Add() created in v2.8.5
//CAIR v2.8.5 Changelog:
// - Added CAIR_HD() which, at each step, determines if the vertical path or the horizontal path has the least energy and then removes it.
// - Changed Energy_Path() so it returns the total energy of the minimum path.
// - Cleaned up unnecessary allocation of some CML objects.
// - Fixed a bug in CML_Matrix:Shift_Row(): bounds checking could cause a shift when one wasn't desired
// - Fixed a bug in Remove_Quadrant(): horrible bounds checking
//CAIR v2.8 Changelog:
// - Now 30% faster across the board.
// - Added CML_Matrix::Shift_Row() which uses memmove() to shift elements in a row of the matrix. Special thanks again to Brett Taylor
// for helping me debug it.
// - Add_Quadrant() and Remove_Quadrant() now use the CML_Matrix::Shift_Row() method instead of the old loops. They also specifically
// handle their own bounds checking for assignments.
// - Removed all bounds checking in CML_Matrix::operator() for a speed boost.
// - Cleaned up some CML functions to directly use the private data instead of the class methods.
// - CML_Matrix::operator=() now uses memcpy() for a speed boost, especially on those larger images.
// - Fixed a bug in CAIR_Grayscale(), CAIR_Edge(), and the CAIR_V/H_Energy() functions: forgot to clear the alpha channel.
// - De-tabbed a few more functions
//CAIR v2.7 Changelog:
// - CML has gone row-major, which made the CPU cache nice and happy. Another 25% speed boost. Unfortunately, all the crazy resizing issues
// from v2.5 came right back, so be careful when using CML_Matrix::Resize_Width() (enlarging requires a Reserve()).
//CAIR v2.6.2 Changelog:
// - Made a ReadMe.txt and Makefile for the package
// - De-tabbed the source files
// - Comment updates
// - Forgot a left-over Temp object in CAIR_Add()
//CAIR v2.6.1 Changelog:
// - Fixed a memory leak in CML_Matrix::Resize_Width()
//CAIR v2.6 Changelog:
// - Eliminated the copying into a temp matrix in CAIR_Remove() and CAIR_Add(). Another 15% speed boost.
// - Fixed the CML resizing so its more logical. No more need for Reserve'ing memory.
//CAIR v2.5 Changelog:
// - Now 35% faster across the board.
// - CML has undergone a major rewrite. It no longer uses vectors as its internal storage. Because of this, its resizing functions
// have severe limitations, so please read the CML comments if you plan to use them. This gave about a 30% performance boost.
// - Optimized Energy_Map(). Now uses two specialized threading functions. About a 5% boost.
// - Optimized Remove_Path() to give another boost.
// - Energy is no longer created and destroyed in Energy_Path(). Gave another boost.
// - Added CAIR_H_Energy(), which gives the horizontal energy of an image.
// - Added CAIR_Removal(), which performs (experimental) automatic object removal. It counts the number of negative weight rows/columns,
// then removes the least amount in that direction. It'll check to make sure it got rid of all negative areas, then it will expand
// the result back out to its original dimensions.
//CAIR v2.1 Changelog:
// - Unrolled the loops for Convolve_Pixel() and changed the way Edge_Detect() works. Optimizing that gave ANOTHER 25% performance boost
// with quality == 1.
// - inline'ed and const'ed a few accessor functions in the CML for a minor speed boost.
// - Fixed a few cross-compiler issues; special thanks to Gabe Rudy.
// - Fixed a few more comments.
// - Forgot to mention, removal of all previous CAIR_DEBUG code. Most of it is in the new CAIR_Edge() and CAIR_Energy() anyways...
//CAIR v2.0 Changelog:
// - Now 50% faster across the board.
// - EasyBMP has been replaced with CML, the CAIR Matrix Library. This gave speed improvements and code standardization.
// This is such a large change it has affected all functions in CAIR, all for the better. Reference objects have been
// replaced with standard pointers.
// - Added three new functions: CAIR_Grayscale(), CAIR_Edge(), and CAIR_Energy(), which give the grayscale, edge detection,
// and energy maps of a source image.
// - Add_Path() and Remove_Path() now maintain Grayscale during resizing. This gave a performance boost with no real
// quality reduction; special thanks to Brett Taylor.
// - Edge_Detect() now handles the boundaries separately for a performance boost.
// - Add_Path() and Remove_Path() no longer refill unchanged portions of an image since CML Resize's are no longer destructive.
// - CAIR_Add() now Reserve's memory for the vectors in CML to prevent memory thrashing as they are enlarged.
// - Fixed another adding bug; new paths have their own artificial weight
//CAIR v1.2 Changelog:
// - Fixed ANOTHER adding bug; now works much better with < 1 quality
// - a few more comment updates
//CAIR v1.1 Changelog:
// - Fixed a bad bug in adding; averaging the wrong pixels
// - Fixed a few incorrect/outdated comments
//CAIR v1.0 Changelog:
// - Path adding now working with reasonable results; special thanks to Ramin Sabet
// - Add_Path() has been multi-threaded
//CAIR v0.5 Changelog:
// - Multi-threaded Energy_Map() and Remove_Path(), gave another 30% speed boost with quality = 0
// - Fixed a few compiler warnings when at level 4 (just stuff in the CAIR_DEBUG code)
//=========================================================================================================//
#include "CAIR.h"
#include "CAIR_CML.h"
#include <cmath> //for abs(), floor()
#include <limits> //for max int
#include <pthread.h>
#include <semaphore.h>
#include <stdint.h>
using namespace std;
//=========================================================================================================//
//Thread parameters
struct Thread_Params
{
//Image Parameters
CML_color * Source;
CML_int * D_Weights;
CAIR_convolution conv;
CAIR_energy ener;
int add_weight;
//Internal Stuff
int * Path;
pthread_mutex_t * Mine; //used only for energy threads
pthread_mutex_t * Not_Mine;
CML_int * Energy_Map;
CML_int * Edge;
CML_gray * Gray;
CML_int * Add_Weight;
CML_int * Sum_Weight;
//Thread Parameters
int top_y;
int bot_y;
int top_x;
int bot_x;
bool exit; //flag causing the thread to exit
};
//=========================================================================================================//
//Thread Info
Thread_Params * thread_info;
//Thread Handles
pthread_t * remove_threads;
pthread_t * edge_threads;
pthread_t * gray_threads;
pthread_t * add_threads;
pthread_t energy_threads[2]; //these are limited to only two
int num_threads = CAIR_NUM_THREADS;
//Thread Semaphores
sem_t remove_sem[3]; //start, edge_start, finish
sem_t add_sem[4]; //add_start, start, edge_start, finish
sem_t edge_sem[2]; //start, finish
sem_t gray_sem[2]; //start, finish
sem_t energy_sem[5]; //start_left, start_right, locks_done, good_to_go, finish
//early declarations on the threading functions
void Startup_Threads();
void Resize_Threads( int height );
void Shutdown_Threads();
//energy thread mutexes. these arrays will be created in Resize_Threads()
pthread_mutex_t * Left_Mutexes = NULL;
pthread_mutex_t * Right_Mutexes = NULL;
int mutex_height = 0;
//=========================================================================================================//
#define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
#define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
//=========================================================================================================//
//== G R A Y S C A L E ==//
//=========================================================================================================//
//=========================================================================================================//
//Performs a RGB->YUV type conversion (we only want Y', the luma)
inline CML_byte Grayscale_Pixel( CML_RGBA * pixel )
{
return (CML_byte)floor( ( 299 * pixel->red +
587 * pixel->green +
114 * pixel->blue ) / 1000.0 );
}
//=========================================================================================================//
//Our thread function for the Grayscale
void * Gray_Quadrant( void * id )
{
int num = (uintptr_t)id;
while( true )
{
//wait for the thread to get a signal to start
sem_wait( &(gray_sem[0]) );
//get updated parameters
Thread_Params gray_area = thread_info[num];
if( gray_area.exit == true )
{
//thread is exiting
break;
}
CML_byte gray = 0;
for( int y = gray_area.top_y; y < gray_area.bot_y; y++ )
{
for( int x = 0; x < (*(gray_area.Source)).Width(); x++ )
{
gray = Grayscale_Pixel( &(*(gray_area.Source))(x,y) );
(*(gray_area.Gray))(x,y) = gray;
}
}
//signal we're done
sem_post( &(gray_sem[1]) );
}
return NULL;
} //end Gray_Quadrant()
//=========================================================================================================//
//Sort-of does a RGB->YUV conversion (actually, just RGB->Y)
//Multi-threaded with each thread getting a stirp across the image.
void Grayscale_Image( CML_color * Source, CML_gray * Dest )
{
int thread_height = (*Source).Height() / num_threads;
//setup parameters
for( int i = 0; i < num_threads; i++ )
{
thread_info[i].Source = Source;
thread_info[i].Gray = Dest;
thread_info[i].top_y = i * thread_height;
thread_info[i].bot_y = thread_info[i].top_y + thread_height;
}
//have the last thread pick up the slack
thread_info[num_threads-1].bot_y = (*Source).Height();
//startup the threads
for( int i = 0; i < num_threads; i++ )
{
sem_post( &(gray_sem[0]) );
}
//now wait for them to come back to us
for( int i = 0; i < num_threads; i++ )
{
sem_wait( &(gray_sem[1]) );
}
} //end Grayscale_Image()
//=========================================================================================================//
//== E D G E ==//
//=========================================================================================================//
enum edge_safe { SAFE, UNSAFE };
//=========================================================================================================//
//returns the convolution value of the pixel Source[x][y] with one of the kernels.
//Several kernels are avaialable, each with their strengths and weaknesses. The edge_safe
//param will use the slower, but safer Get() method of the CML.
int Convolve_Pixel( CML_gray * Source, int x, int y, edge_safe safety, CAIR_convolution convolution)
{
int conv = 0;
switch( convolution )
{
case PREWITT:
if( safety == SAFE )
{
conv = abs( (*Source).Get(x+1,y+1) + (*Source).Get(x+1,y) + (*Source).Get(x+1,y-1) //x part of the prewitt
-(*Source).Get(x-1,y-1) - (*Source).Get(x-1,y) - (*Source).Get(x-1,y+1) ) +
abs( (*Source).Get(x+1,y+1) + (*Source).Get(x,y+1) + (*Source).Get(x-1,y+1) //y part of the prewitt
-(*Source).Get(x+1,y-1) - (*Source).Get(x,y-1) - (*Source).Get(x-1,y-1) );
}
else
{
conv = abs( (*Source)(x+1,y+1) + (*Source)(x+1,y) + (*Source)(x+1,y-1) //x part of the prewitt
-(*Source)(x-1,y-1) - (*Source)(x-1,y) - (*Source)(x-1,y+1) ) +
abs( (*Source)(x+1,y+1) + (*Source)(x,y+1) + (*Source)(x-1,y+1) //y part of the prewitt
-(*Source)(x+1,y-1) - (*Source)(x,y-1) - (*Source)(x-1,y-1) );
}
break;
case V_SQUARE:
if( safety == SAFE )
{
conv = (*Source).Get(x+1,y+1) + (*Source).Get(x+1,y) + (*Source).Get(x+1,y-1) //x part of the prewitt
-(*Source).Get(x-1,y-1) - (*Source).Get(x-1,y) - (*Source).Get(x-1,y+1);
conv *= conv;
}
else
{
conv = (*Source)(x+1,y+1) + (*Source)(x+1,y) + (*Source)(x+1,y-1) //x part of the prewitt
-(*Source)(x-1,y-1) - (*Source)(x-1,y) - (*Source)(x-1,y+1);
conv *= conv;
}
break;
case V1:
if( safety == SAFE )
{
conv = abs( (*Source).Get(x+1,y+1) + (*Source).Get(x+1,y) + (*Source).Get(x+1,y-1) //x part of the prewitt
-(*Source).Get(x-1,y-1) - (*Source).Get(x-1,y) - (*Source).Get(x-1,y+1) );
}
else
{
conv = abs( (*Source)(x+1,y+1) + (*Source)(x+1,y) + (*Source)(x+1,y-1) //x part of the prewitt
-(*Source)(x-1,y-1) - (*Source)(x-1,y) - (*Source)(x-1,y+1) ) ;
}
break;
case SOBEL:
if( safety == SAFE )
{
conv = abs( (*Source).Get(x+1,y+1) + (2 * (*Source).Get(x+1,y)) + (*Source).Get(x+1,y-1) //x part of the sobel
-(*Source).Get(x-1,y-1) - (2 * (*Source).Get(x-1,y)) - (*Source).Get(x-1,y+1) ) +
abs( (*Source).Get(x+1,y+1) + (2 * (*Source).Get(x,y+1)) + (*Source).Get(x-1,y+1) //y part of the sobel
-(*Source).Get(x+1,y-1) - (2 * (*Source).Get(x,y-1)) - (*Source).Get(x-1,y-1) );
}
else
{
conv = abs( (*Source)(x+1,y+1) + (2 * (*Source)(x+1,y)) + (*Source)(x+1,y-1) //x part of the sobel
-(*Source)(x-1,y-1) - (2 * (*Source)(x-1,y)) - (*Source)(x-1,y+1) ) +
abs( (*Source)(x+1,y+1) + (2 * (*Source)(x,y+1)) + (*Source)(x-1,y+1) //y part of the sobel
-(*Source)(x+1,y-1) - (2 * (*Source)(x,y-1)) - (*Source)(x-1,y-1) );
}
break;
case LAPLACIAN:
if( safety == SAFE )
{
conv = abs( (*Source).Get(x+1,y) + (*Source).Get(x-1,y) + (*Source).Get(x,y+1) + (*Source).Get(x,y-1)
-(4 * (*Source).Get(x,y)) );
}
else
{
conv = abs( (*Source)(x+1,y) + (*Source)(x-1,y) + (*Source)(x,y+1) + (*Source)(x,y-1)
-(4 * (*Source)(x,y)) );
}
break;
}
return conv;
}
//=========================================================================================================//
//The thread function, splitting the image into strips
void * Edge_Quadrant( void * id )
{
int num = (uintptr_t)id;
while( true )
{
sem_wait( &(edge_sem[0]) );
//get updated parameters
Thread_Params edge_area = thread_info[num];
if( edge_area.exit == true )
{
//thread is exiting
break;
}
for( int y = edge_area.top_y; y < edge_area.bot_y; y++ )
{
//left most edge
(*(edge_area.Edge))(0,y) = Convolve_Pixel( edge_area.Gray, 0, y, SAFE, edge_area.conv );
//fill in the middle
for( int x = 1; x < (*(edge_area.Gray)).Width() - 1; x++ )
{
(*(edge_area.Edge))(x,y) = Convolve_Pixel( edge_area.Gray, x, y, UNSAFE, edge_area.conv );
}
//right most edge
(*(edge_area.Edge))((*(edge_area.Gray)).Width()-1,y) = Convolve_Pixel( edge_area.Gray, (*(edge_area.Gray)).Width()-1, y, SAFE, edge_area.conv);
}
//signal we're done
sem_post( &(edge_sem[1]) );
}
return NULL;
}
//=========================================================================================================//
//Performs full edge detection on Source with one of the kernels.
void Edge_Detect( CML_gray * Source, CML_int * Dest, CAIR_convolution conv )
{
//There is no easy solution to the boundries. Calling the same boundry pixel to convolve itself against seems actually better
//than padding the image with zeros or 255's.
//Calling itself induces a "ringing" into the near edge of the image. Padding can lead to a darker or lighter edge.
//The only "good" solution is to have the entire one-pixel wide edge not included in the edge detected image.
//This would reduce the size of the image by 2 pixels in both directions, something that is unacceptable here.
int thread_height = (*Source).Height() / num_threads;
//setup parameters
for( int i = 0; i < num_threads; i++ )
{
thread_info[i].Gray = Source;
thread_info[i].Edge = Dest;
thread_info[i].top_y = (i * thread_height) + 1; //handle very top row down below
thread_info[i].bot_y = thread_info[i].top_y + thread_height;
thread_info[i].conv = conv;
}
//have the last thread pick up the slack
thread_info[num_threads-1].bot_y = (*Source).Height() - 1; //handle very bottom row down below
//create the threads
for( int i = 0; i < num_threads; i++ )
{
sem_post( &(edge_sem[0]) );
}
//while those are running we can go back and do the boundry pixels with the extra safety checks
for( int x = 0; x < (*Source).Width(); x++ )
{
(*Dest)(x,0) = Convolve_Pixel( Source, x, 0, SAFE, conv );
(*Dest)(x,(*Source).Height()-1) = Convolve_Pixel( Source, x, (*Source).Height()-1, SAFE, conv );
}
//now wait on them
for( int i = 0; i < num_threads; i++ )
{
sem_wait( &(edge_sem[1]) );
}
} //end Edge_Detect()
//=========================================================================================================//
//== E N E R G Y ==//
//=========================================================================================================//
//=========================================================================================================//
//Simple fuction returning the minimum of three values.
inline int min_of_three( int x, int y, int z )
{
int min = y;
if( x < min )
{
min = x;
}
if( z < min )
{
return z;
}
return min;
}
//=========================================================================================================//
//Get the value from the integer matrix, return a large value if out-of-bounds in the x-direction.
inline int Get_Max( CML_int * Energy, int x, int y )
{
if( ( x < 0 ) || ( x >= (*Energy).Width() ) )
{
return std::numeric_limits<int>::max();
}
else
{
return (*Energy).Get( x, y );
}
}
//=========================================================================================================//
//This calculates a minimum energy path from the given start point (min_x) and the energy map.
//Note: Path better be of proper size.
void Generate_Path( CML_int * Energy, int min_x, int * Path )
{
int min;
int x = min_x;
for( int y = (*Energy).Height() - 1; y >= 0; y-- ) //builds from bottom up
{
min = x; //assume the minimum is straight up
if( Get_Max( Energy, x-1, y ) < Get_Max( Energy, min, y ) ) //check to see if min is up-left
{
min = x - 1;
}
if( Get_Max( Energy, x+1, y ) < Get_Max( Energy, min, y) ) //up-right
{
min = x + 1;
}
Path[y] = min;
x = min;
}
}
//=========================================================================================================//
//Forward energy cost functions. These are additional energy values for the left, up, and right seam paths.
//See the paper "Improved Seam Carving for Video Retargeting" by Michael Rubinstein, Ariel Shamir, and Shai Avidan.
inline int Forward_CostL( CML_int * Edge, int x, int y )
{
return (abs((*Edge)(x+1,y) - (*Edge)(x-1,y)) + abs((*Edge)(x,y-1) - (*Edge)(x-1,y)));
}
inline int Forward_CostU( CML_int * Edge, int x, int y )
{
return (abs((*Edge)(x+1,y) - (*Edge)(x-1,y)));
}
inline int Forward_CostR( CML_int * Edge, int x, int y )
{
return (abs((*Edge)(x+1,y) - (*Edge)(x-1,y)) + abs((*Edge)(x,y-1) - (*Edge)(x+1,y)));
}
//=========================================================================================================//
//threading procedure for Energy Map
//-main signals to start left
//-main waits for left to signal locks_done
//+left starts and locks mutexes
//+left signals main locks_done
//+left waits for good_to_go
//-main starts and signals start right
//-main waits for right to signal locks_done
//#right starts and lock mutexes
//#right signals main locks_done
//#right waits for good_to_go
//-main starts and signals good_to_go twice
//-main waits for finish twice
//+#left and right start and do there thing
//#+left and right signal finish when done
//+#left and right wait for thier start
//-main starts and continues on
//The reason for the crazy mutex locking is because I need to evenly split the matrix in half for each thread.
//So, for the boundry between the two threads, they will try to access a value that the other thread is
//managing. For example, the left thread needs the value of an element on the boundry between the left and right threads.
//It needs the value of the three pixels above it, one of them, the top-right, is managed by the right thread.
//The right thread might not have gotten around to filling that value in, so the Left thread must check.
//It does that by trying to lock the mutex on that value. If the right thread already filled that value in,
//it'll get it immediately and continue. If not, the left thread will block until the right thread gets around
//to filling it in and unlocking the mutex. That means each value along the border has its own mutex.
//The thread responsible for those values must lock those mutexes first before the other thread can try.
//This limits one thread only getting about 2 rows ahead of the other thread before it finds itself blocked.
//=========================================================================================================//
void * Energy_Left( void * id )
{
int num = (uintptr_t)id;
int energy = 0;// current calculated enery
int min_x = 0, max_x = 0;
while( true )
{
sem_wait( &(energy_sem[0]) );
//get the update parameters
Thread_Params energy_area = thread_info[num];
if( energy_area.exit == true )
{
//thread is exiting
break;
}
int * Path = energy_area.Path;
if( Path == NULL )
{
//calculate full region
min_x = energy_area.top_x;
max_x = energy_area.bot_x;
}
else
{
//restrict calculation tree based on path location
min_x = MAX( Path[0]-3, energy_area.top_x );
max_x = MIN( Path[0]+2, energy_area.bot_x );
}
//lock our mutexes
for( int i = 0; i < mutex_height; i++ )
{
pthread_mutex_lock( &(energy_area.Mine)[i] );
}
//signal we are done
sem_post( &(energy_sem[2]) );
//wait until we are good to go
sem_wait( &(energy_sem[3]) );
//set the first row with the correct energy
for( int x = min_x; x <= max_x; x++ )
{
(*(energy_area.Energy_Map))(x,0) = (*(energy_area.Edge))(x,0) + (*(energy_area.D_Weights))(x,0);
}
//now signal that one is done
pthread_mutex_unlock( &(energy_area.Mine)[0] );
for( int y = 1; y < (*(energy_area.Edge)).Height(); y++ )
{
min_x=MAX( min_x-1, energy_area.top_x );
max_x=MIN( max_x+1, energy_area.bot_x );
for( int x = min_x; x <= max_x; x++ )
{
if( x == energy_area.top_x )
{
//being the edge value, forward energy would have no benefit here, and hence is not checked
energy = MIN( (*(energy_area.Energy_Map))(energy_area.top_x,y-1), (*(energy_area.Energy_Map))(energy_area.top_x+1,y-1) )
+ (*(energy_area.Edge))(energy_area.top_x,y) + (*(energy_area.D_Weights))(energy_area.top_x,y);
}
else
{
if( x == energy_area.bot_x )//get access to the bad pixel (the one not maintained by us)
{
pthread_mutex_lock( &(energy_area.Not_Mine)[y-1] );
pthread_mutex_unlock( &(energy_area.Not_Mine)[y-1] );
}
if( energy_area.ener == BACKWARD )
{
//grab the minimum of straight up, up left, or up right
energy = min_of_three( (*(energy_area.Energy_Map))(x-1,y-1),
(*(energy_area.Energy_Map))(x,y-1),
(*(energy_area.Energy_Map))(x+1,y-1) )
+ (*(energy_area.Edge))(x,y) + (*(energy_area.D_Weights))(x,y);
}
else
{
energy = min_of_three( (*(energy_area.Energy_Map))(x-1,y-1) + Forward_CostL(energy_area.Edge,x,y),
(*(energy_area.Energy_Map))(x,y-1) + Forward_CostU(energy_area.Edge,x,y),
(*(energy_area.Energy_Map))(x+1,y-1) + Forward_CostR(energy_area.Edge,x,y) )
+ (*(energy_area.D_Weights))(x,y);
}
}
//now we have the energy
if((*(energy_area.Energy_Map))(x,y) == energy && Path != NULL )
{
if(x == min_x && Path[y]>min_x+3 )min_x++;
if(x == max_x && Path[y]<max_x-2 )max_x--;
}
else
{ //set the energy of the pixel
(*(energy_area.Energy_Map))(x,y) = energy;
}
}
pthread_mutex_unlock( &(energy_area.Mine)[y] );
}
//signal we're done
sem_post( &(energy_sem[4]) );
} //end while(true)
return NULL;
} //end Energy_Left()
//=========================================================================================================//
void * Energy_Right( void * id )
{
int num = (uintptr_t)id;
int energy = 0;// current calculated enery
int min_x = 0, max_x = 0;
while( true )
{
sem_wait( &(energy_sem[1]) );
//get the update parameters
Thread_Params energy_area = thread_info[num];
int * Path = energy_area.Path;
if( energy_area.exit == true )
{
//thread is exiting
break;
}
if( Path == NULL )
{
min_x = energy_area.top_x;
max_x = energy_area.bot_x;
}
else
{
min_x = MAX( Path[0]-3, energy_area.top_x );
max_x = MIN( Path[0]+2, energy_area.bot_x );
}
//lock our mutexes
for( int i = 0; i < mutex_height; i++ )
{
pthread_mutex_lock( &(energy_area.Mine)[i] );
}
//signal we are done
sem_post( &(energy_sem[2]) );
//wait until we are good to go
sem_wait( &(energy_sem[3]) );
//set the first row with the correct energy
for( int x = min_x; x <= max_x; x++ )
{
(*(energy_area.Energy_Map))(x,0) = (*(energy_area.Edge))(x,0) + (*(energy_area.D_Weights))(x,0);
}
//now signal that one is done
pthread_mutex_unlock( &(energy_area.Mine)[0] );
for( int y = 1; y < (*(energy_area.Edge)).Height(); y++ )
{
min_x = MAX( min_x-1, energy_area.top_x );
max_x = MIN( max_x+1, energy_area.bot_x );
for( int x = min_x ; x <= max_x; x++ ) //+1 because we handle that seperately
{
if( x == energy_area.bot_x )
{
//being the edge value, forward energy would have no benefit here, and hence is not checked
energy = MIN( (*(energy_area.Energy_Map))(energy_area.bot_x,y-1), (*(energy_area.Energy_Map))(energy_area.bot_x-1,y-1) )
+ (*(energy_area.Edge))(energy_area.bot_x,y) + (*(energy_area.D_Weights))(energy_area.bot_x,y);
}
else
{
if(x == energy_area.top_x )//get access to the bad pixel (the one not maintained by us)
{
pthread_mutex_lock( &(energy_area.Not_Mine)[y-1] );
pthread_mutex_unlock( &(energy_area.Not_Mine)[y-1] );
}
if( energy_area.ener == BACKWARD )
{
//grab the minimum of straight up, up left, or up right
energy = min_of_three( (*(energy_area.Energy_Map))(x-1,y-1),
(*(energy_area.Energy_Map))(x,y-1),
(*(energy_area.Energy_Map))(x+1,y-1) )
+ (*(energy_area.Edge))(x,y) + (*(energy_area.D_Weights))(x,y);
}
else
{
energy = min_of_three( (*(energy_area.Energy_Map))(x-1,y-1) + Forward_CostL(energy_area.Edge,x,y),
(*(energy_area.Energy_Map))(x,y-1) + Forward_CostU(energy_area.Edge,x,y),
(*(energy_area.Energy_Map))(x+1,y-1) + Forward_CostR(energy_area.Edge,x,y) )
+ (*(energy_area.D_Weights))(x,y);
}
}
//now we have the energy
if( (*(energy_area.Energy_Map))(x,y) == energy && Path != NULL )
{
if( x == min_x && Path[y] > x+3 ) min_x++;
if( x == max_x && Path[y] < x-2 ) max_x--;
}
else
{//set the energy of the pixel
(*(energy_area.Energy_Map))(x,y) = energy;
}
}
pthread_mutex_unlock( &(energy_area.Mine)[y] );// could be put in the loop for faster a releasing of the mutex, but to be VERY carefull (use a boolean on the previous lock)
}
//signal we're done
sem_post( &(energy_sem[4]) );
} //end while(true)
return NULL;
} //end Energy_Right()
//=========================================================================================================//
//Calculates the energy map from Edge, adding in Weights where needed. The Path is used to determine how much of the
//given Map is to remain unchanged. A Path of NULL will cause the Map to be fully recalculated.
void Energy_Map( CML_int * Edge, CML_int * Weights, CML_int * Map, CAIR_energy ener, int * Path )
{
//set the paramaters
//left side
thread_info[0].Edge = Edge;
thread_info[0].D_Weights = Weights;
thread_info[0].Energy_Map = Map;
thread_info[0].Path = Path;
thread_info[0].top_x = 0;
thread_info[0].bot_x = (*Edge).Width() / 2;
thread_info[0].ener = ener;
thread_info[0].Mine = Left_Mutexes;
thread_info[0].Not_Mine = Right_Mutexes;
//the right side
thread_info[1] = thread_info[0];
thread_info[1].top_x = thread_info[0].bot_x + 1;
thread_info[1].bot_x = (*Edge).Width() - 1;
thread_info[0].Mine = Right_Mutexes;
thread_info[0].Not_Mine = Left_Mutexes;
//startup the left
sem_post( &(energy_sem[0]) );
//wait for it to lock
sem_wait( &(energy_sem[2]) );
//startup the right
sem_post( &(energy_sem[1]) );
//wait for it to lock
sem_wait( &(energy_sem[2]) );
//fire them up
sem_post( &(energy_sem[3]) );
sem_post( &(energy_sem[3]) );
//now wait on them
sem_wait( &(energy_sem[4]) );
sem_wait( &(energy_sem[4]) );
} //end Energy_Map()
//=========================================================================================================//
//Energy_Path() generates the least energy Path of the Edge and Weights and returns the total energy of that path.
//This uses a dynamic programming method to easily calculate the path and energy map (see wikipedia for a good example).
//Weights should be of the same size as Edge, Path should be of proper length (the height of Edge).
int Energy_Path( CML_int * Edge, CML_int * Weights, CML_int * Energy, int * Path, CAIR_energy ener, bool first_time )
{
(*Energy).Resize_Width( (*Edge).Width() );
//calculate the energy map
if( first_time == true )
{
Energy_Map( Edge, Weights, Energy, ener, NULL );
}
else
{
Energy_Map( Edge, Weights, Energy, ener, Path );
}
//find minimum path start
int min_x = 0;
for( int x = 0; x < (*Energy).Width(); x++ )
{
if( (*Energy)(x, (*Energy).Height() - 1 ) < (*Energy)(min_x, (*Energy).Height() - 1 ) )
{
min_x = x;
}
}
//generate the path back from the energy map
Generate_Path( Energy, min_x, Path );
return (*Energy)( min_x, (*Energy).Height() - 1 );
}
//=========================================================================================================//
//== A D D ==//
//=========================================================================================================//
//=========================================================================================================//
//averages two pixels and returns the values
CML_RGBA Average_Pixels( CML_RGBA Pixel1, CML_RGBA Pixel2 )
{
CML_RGBA average;
average.alpha = ( Pixel1.alpha + Pixel2.alpha ) / 2;
average.blue = ( Pixel1.blue + Pixel2.blue ) / 2;
average.green = ( Pixel1.green + Pixel2.green ) / 2;
average.red = ( Pixel1.red + Pixel2.red ) / 2;
return average;
}
//=========================================================================================================//
//This works like Remove_Quadrant, stripes across the image.
void * Add_Quadrant( void * id )
{
int num = (uintptr_t)id;
Thread_Params add_area;
while( true )
{
sem_wait( &(add_sem[0]) );
//get updated_parameters
add_area = thread_info[num];
if( add_area.exit == true )
{
//thread is exiting
break;
}
//first add the weights with the artificial weights
//Adds the two weight matrircies, Weights and the artifical weight, into Sum.
//This is so the new-path artificial weight doesn't poullute our input Weight matrix.
for( int y = add_area.top_y; y < add_area.bot_y; y++ )
{
for( int x = 0; x < (*(add_area.D_Weights)).Width(); x++ )
{
(*(add_area.Sum_Weight))(x,y) = (*(add_area.Add_Weight))(x,y) + (*(add_area.D_Weights))(x,y);
}
}
//signal that part is done
sem_post( &(add_sem[3]) );
//wait to begin the next part
sem_wait( &(add_sem[1]) );
//get updated_parameters
add_area = thread_info[num];
for( int y = add_area.top_y; y < add_area.bot_y; y++ )
{
int add = (add_area.Path)[y];
//shift over everyone to the right
(*(add_area.Source)).Shift_Row( add, y, 1 );
(*(add_area.Add_Weight)).Shift_Row( add, y, 1 );
(*(add_area.D_Weights)).Shift_Row( add, y, 1 );
(*(add_area.Gray)).Shift_Row( add, y, 1 );
(*(add_area.Energy_Map)).Shift_Row( add, y, 1 );
//go back and set the added pixel
(*(add_area.Source))(add,y) = Average_Pixels( (*(add_area.Source))(add,y), (*(add_area.Source)).Get(add-1,y));
(*(add_area.D_Weights))(add,y) = ( (*(add_area.D_Weights))(add,y) + (*(add_area.D_Weights)).Get(add-1,y) ) / 2;
(*(add_area.Gray))(add,y) = Grayscale_Pixel( &(*(add_area.Source))(add,y) );