blib/lib/Image/PHash.pm

filter: Statementstmt 26.8% 75 / 279 Branchbran 20.1% 33 / 164 Conditioncond 22.2% 22 / 99 MC/DCmcdc 10.7% 6 / 56 Subroutinesub 34.2% 12 / 35 Podpod 100% 9 / 9 totaltotal 24.4% 157 / 642 CC 133 SCAR 49.8
CC
133
Cov
24%
pHash
600.0
printbitmatrix
210.0
new
120.0
CRAP 145.7
↑ Summary
1 package Image::PHash;
2  
3 5 ▶use 5.008;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 5 ▶no warnings "portable";
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 5 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 5 ▶use Config;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 5 ▶use Math::DCT 'dct2d';
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 5 our $VERSION = '0.3';
13  
14 =head1 NAME
15  
16 Image::PHash - Fast perceptual image hashing (DCT-based pHash)
17  
18 =head1 SYNOPSIS
19  
20 use Image::PHash;
21  
22 # Load an image and prepare to hash.
23 # Will try to find an image library to load and resize the image to 32x32, ready for the DCT step
24 my $iph = Image::PHash->new($image_file);
25  
26 # Calculate the perceptual hash (top 8x8 of the DCT) - 64 bits, 16 hex chars
27 my $p = $iph->pHash(); # implies settings geometry => '8x8', method => 'average'
28  
29 # Alternative, better performing, 64 bit hash (64 upper-left most DCT values)
30 my $p = $iph->pHash(geometry => 64); # this is actually recommended over the default hash
31  
32 # Alternative method for creating the bitmask with lower false-negative rate
33 my $p = $iph->pHash(geometry => 64, method => 'log');
34  
35 # Calculate a pHash with the upper left half of the upper-left-most 7x7 of the DCT - 27 bits, 7 hex chars
36 # Use for indexing or reducing full phash false negatives - significant false negative rate by itself
37 my $p7 = $iph->pHash(geometry => '7x7', reduce => 1);
38 # or shortcut function
39 $p7 = $iph->pHash7();
40  
41 # Calculate a pHash with the upper left half of the upper-left-most 6x6 of the DCT - 20 bits, 5 hex chars
42 # Use for indexing or reducing full phash false negatives - very significant false negative rate by itself
43 my $p6 = $iph->pHash(geometry => '6x6', reduce => 1, method => 'median');
44 # or shortcut function
45 $p6 = $iph->pHash6();
46  
47 # Calculate the difference (Hamming distance) between two hex hashes
48 my $diff = Image::PHash::diff($p1, $p2);
49  
50 =head1 DESCRIPTION
51  
52 Image::PHash allows you to calculate the (DCT-based) perceptual hash (pHash) of an image.
53  
54 The constructor and general structure is based on L<Image::Hash> - keeping usage quite
55 similar, but the pHash algorithm is rewritten from scratch as the L<Image::Hash>
56 implementation was flawed (and slow). Apart from fixes/tweaks for L<GD>, L<Imager>,
57 L<ImageMagick> resizing, L<Image::Imlib2> support is added along with some unique features
58 like reduced hashes for indexing, options to deal with image mirroring, alternative
59 bitmap methods.
60  
61 A fast DCT XS module made specifically to serve this hashing module is used: L<Math::DCT>.
62 Depending on your setup, it should be 15x or so faster than pHash.org
63  
64 =head1 CONSTRUCTOR METHOD
65  
66 =head2 C<new>
67  
68 my $iph = Image::PHash->new($image_file , $library?, \%settings?);
69
70 The first argument is an image filename when the Imlib2 library is used, but it
71 can also by a variable with the image data for the other libraries, or even an
72 image object for the supported libraries.
73  
74 The second (optional) argument is the image library. Valid options are C<Imlib2>,
75 C<GD>, C<Imager>, C<ImageMagick> and if not specified the module will try to load
76 them in that order. Using a different library (or even library version) will most
77 likely result in different hashes being returned, so make sure you hash your entire
78 image set using the same image library. Also, the module will probably not work with
79 very old versions of the image libraries. See Notes for comparison of libraries.
80  
81 The third (optional) argument can take a reference to a settings hash. Currently
82 supported settings:
83  
84 =over 4
85  
86 =item * C<resize> : Expects an integer to specify the size of the image resize before
87 applying the DCT transformation. By default it is C<32>, which resizes to a C<32x32> image.
88 You may want to explore different sizes which have different hashing behaviour e.g.
89 increasing resize to C<64> seems to offer some benefit for the reduced/index hashes
90 (at a performance penalty of course).
91  
92 =item * C<magick_filter> : The C<filter> parameter for L<ImageMagick> which controls
93 the scaling filter. The default is C<Cubic> which is about as good as L<ImageMagick>'s
94 own default C<Lanczos>, but significantly faster. You can look up the L<ImageMagick>
95 documentation for alternatives (e.g. C<Lanczos>, C<Mitchell>, C<Triangle>, C<Gaussian>...)
96 if you want a different balance of speed/quality.
97  
98 =item * C<imager_qtype> : The C<qtype> parameter for L<Imager> which defines the
99 quality of scaling performed. The type C<mixing> is used by default as it seems to
100 behave well for most cases while being about twice as fast as L<Imager>'s internal
101 default qtype of C<normal>, but you can still manually specify that if you prefer.
102  
103 The constructor will C<croak> if there is an error loading an image library or an
104 incorrect/missing argument. It will only C<carp> and return C<undef> if an image
105 library returns after failing to load an image.
106  
107 =back
108  
109 =head1 METHODS
110  
111 =head2 C<pHash>
112  
113 my $p = $iph->pHash(
114 geometry => '8x8', # Size of the matrix to keep from the DCT. 8x8 is the standard 64 bit pHash.
115 reduce => 0, # If enabled removes lower right half or matrix and 0,0 position.
116 method => 'average', # Method with which to convert the dct to bitmask.
117 mirror => 0, # If enabled will return the hash of the mirror image (horizontal flip).
118 mirrorproof => 0, # If enabled will return a hash type that resists image mirroring.
119 );
120  
121 my @bits = $iph->pHash();
122  
123 Generates a pHash, returns it as a hex string (or array of 1s and 0s in array
124 context).
125  
126 The pHash process consists of resizing the image to 32x32 (unless different C<resize>)
127 was specified with the constructor, converting color to luminance, DCT on resized image's
128 luminance, conversion to bit values based on the selected method and dropping the high
129 frequency part of the matrix, following the C<geometry> and C<reduce> settings.
130  
131 The parameters to pass:
132  
133 =over 4
134
135 =item * C<geometry> : A string with the desired square dimensions C<NxN> of the bit
136 matrix taken from the upper left of the full (by default 32x32) processed DCT to be
137 used in the hash. By default it is C<'8x8'>, which produces the typical 64bit pHash.
138  
139 Alternatively, specify a simple integer for the number of low frequency bits to take
140 from the matrix going through the matrix in increasing diagonals.
141 E.g. a value of C<64> will return 64 bits just like the default pHash, but they will
142 be taken from the upper left half of the 11x11 top-left part of the DCT matrix. The
143 effect is that the resulting hash will have improved characteristics, especially
144 in the average distance of non-similar images.
145  
146 =item * C<reduce> : The option will return only the bits that are on, or to the upper
147 left of the 0,N->N,0 diagonal of the selected NxN matrix, except the first bit (which
148 is always 1). This way you get the (N-1)*(2+N)/2 most significant (recording the largest
149 changes) bits.
150  
151 For example, a 8x8 reduced hash has 35 bits, which is less than a 6x6 matrix, and yet
152 may outperform a full 7x7 49 bit matrix.
153  
154 The option only applies to square C<geometry>. If you have specified bits instead,
155 you already get an effect similar to C<reduce>.
156  
157 =item * C<method> : Specifies which method to use for converting the DCT result to
158 a bitmask. By default it is C<average>. Supported methods:
159  
160 =over 4
161  
162 =item * C<average> : The default method which compares each DCT value with the arithmetic
163 mean. It usually a bit better at recognising similarity than C<median> (the average
164 difference of similar images will be lower), albeit with an increase in false positives.
165  
166 =item * C<median> : The median of the DCT values is used as the threshold. Some
167 implementations prefer it over C<average> due to lower false positives/collision rate,
168 which can be good for reduced size hashes, but it increases false negatives so it is
169 not the recommended method for many scenarios.
170  
171 =item * C<average_x> : Applies only to reduced hashes - it will calculate the average using
172 the entire NxN matrix for C<geometry='NxN'>, or use the next X lowest frequency DCT coefficients
173 (total 2*X) to calculate the average for C<geometry=X>. Almost as low collision rate as C<log>,
174 perhaps a bit better (lower) false negatives.
175  
176 =item * C<log> : A special logarithmic average is calculated as the threshold, giving
177 the lowest collision rate (a tie with <median> or better). It will usually have a bit
178 increased false negative chance compared to C<average> or perhaps even C<diff> - but
179 should still be lower than C<median>. Quite close to C<average_x>, but also applies to
180 non-reduced hashes.
181  
182 =item * C<diff> : The difference between each DCT value is taken as the bitmask. It seems
183 to fall between C<average> and C<median> in most tests, both in false negative/collision
184 rate and at similarity recognition.
185  
186 =back
187  
188 =item * C<mirror> : Returns the pHash of the mirror image. Note that this is a function
189 applied after the DCT, so if you call C<pHash> once with C<mirror> and once without
190 you can get both hashes without a processing overhead. Not compatible with C<mirrorproof>.
191  
192 =item * C<mirrorproof> : Will return a pHash that is impervious to mirroring (flipping
193 images horizontally). This means two mirrored images will have the same/similar pHash,
194 so it is good for declaring such images as "similar" with a single pHash comparison, but
195 if you want to know they were mirrored the C<mirror> option is more appropriate.
196  
197 Caveat: The option sacrifices about 2 bits or so of entropy, so the resulting
198 pHash is less effective. Thus, it should not be preferred if there is no specific
199 reason, especially when the C<mirror> option is available.
200  
201 =back
202  
203 =head1 INDEXING SHORTCUT METHODS
204  
205 The special reduced hashes below, named B<pHash6> and B<pHash7> are specially chosen
206 to be useful in two scenarios:
207 * Extra verification to reduce false positives that the full has produces. Depending
208 on the scenario, tests have shown each of the reduced hash being able to reduce false
209 positives by 60-90% with the right threshold (example 2, 3 for pHash6, pHash7 resp.),
210 and if both are used over 95% reduction of false positives is possible.
211 * For scenarios where we want to use a simple index of a database (e.g. MySQL) and only
212 very simple manipulations are required to be matched (e.g. resize) or there is a higher
213 tolerance for false negatives, pHash6 & pHash7 at diff 0 can be used to retrieve most
214 matches. For example, storing pHash6, pHash7 (as indices) along with pHash in a MySQL db,
215 we can retrieve most matches with something like:
216  
217 SELECT *
218 FROM hash_table
219 WHERE (phash7 = @phash7
220 OR phash6 = @phash6)
221 AND BIT_COUNT(CAST(CONV(phash, 16, 10) AS UNSIGNED) ^ CAST(CONV(@phash, 16, 10) AS UNSIGNED)) < 8;
222  
223  
224 =head2 C<pHash7>
225  
226 my $p7 = $iph->pHash7();
227  
228 Equivalent to C<$iph-E<gt>pHash(geometry =E<gt> '7x7', reduce =E<gt> 1)>. It is useful for
229 relational databases that don't support indexing with differences, so using the reduced
230 pHash will return many of the close full pHash matches. For simple resize/compression manipulations
231 expect matches in the region of 98% or so to be returned. It can also be used to verify
232 the match in some cases where a specific pattern might make different photos match in
233 the full phash but not the limited. It takes the same parameters as C<pHash>.
234  
235 =head2 C<pHash6>
236  
237 my $p6 = $iph->pHash6();
238  
239 Equivalent to C<$iph-E<gt>pHash(geometry =E<gt> '6x6', reduce =E<gt> 1, method =E<gt> 'median')>. Similar
240 to pHash7, but will produce more matches when used as an index, along with many more false
241 positives.
242  
243 Note that neither reduced version is appropriate to use as an image comparison hash by itself
244 (too many false positives), and they are chosen to be complimentary, so when used in conjunction
245 for either indexing or verification, their performance increases considerably.
246  
247 =head1 HELPER METHODS
248  
249 =head2 C<reducedimage>
250  
251 my $img = $iph->reducedimage();
252  
253 Returns the reduced (rescaled) image that will be used for the DCT.
254  
255 =head2 C<dctdump>
256  
257 my $dct = $iph->dctdump();
258  
259 Will return the full 32x32 DCT as an arrayref of floats.
260  
261 =head2 C<printbitmatrix>
262  
263 $iph->printbitmatrix(
264 %phash_opt, # Any pHash method option applies
265 separator => '', # Separator for horizontal values
266 filler => ' ' # For reduced results, filler for the missing positions
267 );
268  
269 Will return a print-friendly reduced size bitmask matrix as a string. Basically a
270 string with rows/columns of the 1s and 0s you would get from calling C<$iph-E<gt>pHash()>
271 with the same parameters.
272  
273 =head1 HELPER FUNCTIONS
274  
275 =head2 C<b2h>
276  
277 my $hash = Image::PHash::b2h(join('', @bits));
278  
279 Will convert a bit value string to a hex string.
280  
281 =head2 C<diff>
282  
283 my $diff = Image::PHash::diff($phash1, $phash2);
284  
285 Will calculate the bit difference of two hex string hashes (their Hamming distance
286 of their bit stream form). On 64 bit systems (checking C<$Config{ivsize}>) it will
287 actually call C<_diff64> which can calculate the difference of up to 64bit hashes in
288 a single operation (using C<%064b>). You can call C<_diff64> directly if you prefer
289 in that scenario.
290  
291 =head1 NOTES
292  
293 =head2 Performance
294  
295 The hashing performance of the module is enough to make the actual pHash generation
296 from the final 32x32 mono image a trivial part of the process. For a general idea,
297 on a single core of a 2015 Macbook Pro, over 18000 hashes/sec can be processed thanks
298 in part to the fast L<Math::DCT> XS module (developed specifically for Image::PHash).
299  
300 So, most of the processing time is spent on loading the image, resizing, extracting
301 pixel values, removing color, all of which depend on the specific image module. On an
302 Apple M1, hashing 800x600 jpg images was measured at 131 h/s with L<Image::Magick>,
303 208 h/s with L<Imager>, 241 h/s with L<GD>, 547 h/s with L<Image::Imlib2>.
304 Higher resolutions make the process slower as you could expect. Since all images will
305 be resized to 32x32 in the end, the fastest hashing performance would be if you loaded
306 32x32 thumbnails. In that case, the performance of the libraries in the same order for
307 the resized imageset were: 659 h/s, 664 h/s, 1883 h/s, 2296 h/s. It is clear that
308 L<Image::Imlib2> should be preferred when hashing performance is desired, as it offers
309 dramatically better performance (unless you are hashing 32x32 images in which case L<GD>
310 also fast). It should be noted that the resulting hashes don't have exactly the same
311 behaviour/metrics, due to the different resizing algorithms used, but the differences
312 seem to be very small. You are encouraged to test on your own data set.
313  
314 Remember, never mix image libraries (or settings), the hashes will most likely not
315 be compatible.
316  
317 Finally, if you are curious about the performance of this module compared to the
318 C++ pHash.org implementation, pHash.org could achieve 33 h/s with the test setup as
319 above, making L<Image::PHash> over 16x faster with Imlib2. With pre-sized 32x32
320 images, pHash.org ran at 101 h/s (~23x slower than L<Image::PHash>/Imlin2).
321  
322 =head2 Compatibility of hashes
323  
324 As already mentioned, if you produce hashes with different settings, different image
325 libraries etc, the hashes might not be compatible. It is advisable to even freeze
326 the version of this module and the image library in a production environment to
327 avoid any degraded performance.
328  
329 =head2 Calculation caching
330  
331 Calculating pHashes with different dct/reduce/median/mirror arguments for the same
332 image is very fast (when the same object is used), as the resize and DCT transform
333 will only happen on the very first pHash calculation and are cached for any subsequent
334 call. You can essentially get the extra phash6/phash7/mirror etc "for free" after
335 the initial pHash calculation.
336  
337 =head2 L<Image::PHash> vs L<Image::Hash>
338  
339 While L<Image::Hash> may still be useful for the aHash and dHash functionality, its
340 pHash implementation is seriously flawed. It does not actually do a full DCT, using
341 instead a shortcut that seems to result to hashes with lots of zeros and thus a high
342 rate of collisions (~2% chance for identical hash on dissimilar images making it useless
343 for my large data set), which is the reason the hashing was implemented from scratch.
344 Despite it not doing a full DCT it was really slow (over 80x slower than the XS L<Math::DCT>),
345 so switching to L<Image::PHash> will give you "correct" hashes at a significant speed
346 increase, along with several extra features.
347  
348 =head2 L<Image::PHash> vs L<pHash.org>
349  
350 Apart from the significant speed advantage of Image::PHash noted above, there are a couple
351 of important differences, in that pHash.org will apply a 7x7 mean filter to the image
352 before the resize and the conversion to bits is always done with the median method. This
353 seems to keep false positives quite low, but its false negatives are higher. Since with
354 Image::PHash you can get even better hashes with, for example, C<geometry=64> and you can
355 combine them with C<method='average_x'> or C<method='log'>, you will get even lower false
356 positive rate than pHash.org, but with less false negatives as well. Feel free to share
357 your own comparisons with the author if in doubt.
358  
359 Note that the differences you are to use as a threshold for Image::PHash and pHash.org are
360 quite different - pHash.org will give about 50% greater diffs on average (e.g. where I would
361 use 7 for the former, 11 would be the equivalent for the latter).
362  
363 =head2 Selecting a C<diff> threshold
364  
365 The appropriate C<diff> threshold for declaring images as "similar" is not a precise
366 art and will depend on the application (type of images, tolerance for false positives
367 etc.). The exact application is very important too, if you have 2 images and want to
368 check whether they are similar, a false positive rate of even over 1% is fine, in which
369 case the diff can be chosen to be probably over 10, whereas having a big collection of
370 photos in which you want to check whether a duplicate exists, requires a very low false
371 positive rate. Example diff ranges for a full pHash are 3-7 if you want to keep false
372 positives close to 0%. For the small pHash7 and pHash6 probably not more than 3 and 2
373 respectively are useful for lookups (and still with lots of false positives as noted above).
374  
375 =cut
376  
377 5 my $_64bit;
378  
379 0 ▶sub pHash7 {
Subroutine pHash7: not called CC=1 SCAR=6.9
Pod documented
380 0 my ($self, %opt) = @_;
381 0 return $self->pHash(%opt, geometry => '7x7', reduce => 1);
382 }
383  
384 0 ▶sub pHash6 {
Subroutine pHash6: not called CC=1 SCAR=6.9
Pod documented
385 0 my ($self, %opt) = @_;
386 0 return $self->pHash(%opt, geometry => '6x6', reduce => 1, method => 'median');
387 }
388  
389 10 ▶sub new {
Subroutine new: called CC=41 SCAR=47.9
Pod documented
390 10 my $class = shift;
391  
392 10 my $self = {};
393 10 bless($self, $class);
394  
395 10 ▶ $self->{image} = shift || croak("Image file or data expected.");
Condition100%2/2
shift() || croak('Image file or data expected.')
l!l
91
MC/DC100%1/1
shift() || croak('Image file or data expected.')
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
396 9 $self->{module} = shift;
397 9 ▶ $self->{settings} = shift || {};
Condition100%2/2
shift() || {}
l!l
27
MC/DC100%1/1
shift() || {}
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
398  
399 9 ▶ croak("Hashref expected for settings argument") unless ref($self->{settings}) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self->{"settings"} eq "HASH" 1 8 9
400 8 ▶ $self->{dct_size} = int($self->{settings}->{resize} || 32);
Condition100%2/2
$self->{'settings'}{'resize'} || 32
l!l
17
MC/DC100%1/1
$self->{'settings'}{'resize'} || 32
$self->{'settings'}{'resize'}
Truth table100%2/2
A
A= $self->{'settings'}{'resize'}
Aresult
11
00
401 8 ▶ $self->{imager_qtype} = $self->{settings}->{imager_qtype} || 'mixing';
Condition50%1/2
$self->{'settings'}{'imager_qtype'} || 'mixing'
l!l
08
MC/DC0%0/1
$self->{'settings'}{'imager_qtype'} || 'mixing'
$self->{'settings'}{'imager_qtype'}
Truth table50%1/2
A
A= $self->{'settings'}{'imager_qtype'}
Aresult
11
00
402 8 ▶ $self->{magick_filter} = $self->{settings}->{magick_filter} || 'Cubic';
Condition50%1/2
$self->{'settings'}{'magick_filter'} || 'Cubic'
l!l
08
MC/DC0%0/1
$self->{'settings'}{'magick_filter'} || 'Cubic'
$self->{'settings'}{'magick_filter'}
Truth table50%1/2
A
A= $self->{'settings'}{'magick_filter'}
Aresult
11
00
403 8 ▶ croak("resize > 5 expected.") unless $self->{dct_size} > 5;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"dct_size"} > 5 1 7 8
404  
405 7 my %libs = ( # Library, reduce/resize function, pixels function, support for passing data variable
406 Imlib2 => ['Image::Imlib2', \&_reduce_Imlib2, \&_pixels_Imlib2],
407 GD => ['GD', \&_reduce_GD, \&_pixels_GD, 1],
408 ImageMagick => ['Image::Magick', \&_reduce_Magick, \&_pixels_Magick, 1],
409 Imager => ['Imager', \&_reduce_Imager, \&_pixels_Imager, 1],
410 );
411  
412 7 my $ref = ref($self->{image});
413 7 ▶ my $file = $ref ? undef : -f $self->{image};
Branch: 1 branch
BranchTrueFalseTotal
$ref ? : 1 6 7
414  
415 7 ▶ if ($ref) { # Passed image object
Branch: 2 branches
BranchTrueFalseTotal
if ($ref) { } 1 6 7
elsif ($self->{'module'}) { } 1 5 6
416 1 $self->{module} = undef;
417 1 foreach (_lib_order()) {
418 4 ▶ my $type = $_ eq 'GD' ? 'GD::Image' : $libs{$_}->[0];
Branch: 1 branch
BranchTrueFalseTotal
$_ eq 'GD' ? : 1 3 4
419 4 ▶ if ($type eq $ref) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq $ref) 0 4 4
420 0 $self->{module} = $_;
421 0 last;
422 }
423 }
424 1 ▶ croak("Object of unknown type $ref.") unless $self->{module};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"module"} 1 0 1
425 } elsif ($self->{module}) { # User specified image module
426 1 $libs{$libs{$_}->[0]} = $libs{$_} for keys %libs; # Allow synonyms
427 1 my $lib = $libs{$self->{module}}->[0];
428  
429 croak("Unknown image library specified: '$self->{module}'. "
430 1 ▶ . "Choose from: ".join(', ', map {/:/ ? () : $_} keys %libs)
Branch: 2 branches
BranchTrueFalseTotal
unless $lib 1 0 1
/:/ ? : 2 5 7
431 ) unless $lib;
432  
433 0 ▶ eval "require $lib"
Branch: 1 branch
BranchTrueFalseTotal
eval "require $lib" or croak(qq[Specified image library '$self->{"module"}' could not be loaded.]) 0 0 0
434 or croak("Specified image library '$self->{module}' could not be loaded.");
435  
436 0 $self->{module} = $lib; # Normalize
437 } else {
438 # Try to load Imlib2, GD, Imager, ImageMagick in that order
439 5 foreach my $lib (_lib_order()) {
440 15 ▶ if (eval "require $libs{$lib}->[0]" && ($file || $libs{$lib}->[3])) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval "require $libs{$lib}[0]" and $file || $libs{$lib}[3]) 5 10 15
Condition66%4/6
eval "require $libs{$lib}[0]" and $file || $libs{$lib}[3]
!ll&&!rl&&r
1005
$file or $libs{$lib}[3]
l!l&&r!l&&!r
410
MC/DC33%1/3
eval "require $libs{$lib}[0]" and $file || $libs{$lib}[3]
eval "require $libs{$lib}[0]" $file $libs{$lib}[3]
Truth table75%3/4
A and B or C
A= eval "require $libs{$lib}[0]"B= $fileC= $libs{$lib}[3]
ABCresult
0XX0
1000
11X1
1011
441 5 $self->{module} = $lib;
442 5 last;
443 }
444 }
445 croak("None of the supported image libraries could be loaded. "
446 . " Tried loading: ".join(', ', keys %libs)
447 5 ▶ ) unless $self->{module};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"module"} 0 5 5
448 }
449 croak("No file at $self->{image}")
450 5 ▶ unless $ref || $file || (length($self->{image}) > 255 && $libs{$self->{module}}->[3]);
Branch: 1 branch
BranchTrueFalseTotal
unless $ref or $file or length $self->{"image"} > 255 and $libs{$self->{"module"}}[3] 1 4 5
Condition55%5/9
$ref or $file or length $self->{"image"} > 255 and $libs{$self->{"module"}}[3]
l!l&&r!l&&!r
401
$ref or $file
l!l&&r!l&&!r
041
length $self->{"image"} > 255 and $libs{$self->{"module"}}[3]
!ll&&!rl&&r
100
MC/DC25%1/4
$ref or $file or length $self->{"image"} > 255 and $libs{$self->{"module"}}[3]
$ref $file length $self->{"image"} > 255 $libs{$self->{"module"}}[3]
Truth table40%2/5
A or B or C and D
A= $refB= $fileC= length $self->{"image"} > 255D= $libs{$self->{"module"}}[3]
ABCDresult
1XXX1
01XX1
00111
000X0
00100
451  
452 4 my $error = '';
453 4 ▶ if ($libs{$self->{module}}->[0] eq 'Image::Imlib2') {
Branch: 3 branches
BranchTrueFalseTotal
if ($libs{$self->{'module'}}[0] eq 'Image::Imlib2') { } 0 4 4
elsif ($libs{$self->{'module'}}[0] eq 'GD') { } 0 4 4
elsif ($libs{$self->{'module'}}[0] eq 'Image::Magick') { } 0 4 4
454 0 ▶ $self->{im} = $ref ? $self->{image} : Image::Imlib2->load($self->{image});
Branch: 1 branch
BranchTrueFalseTotal
$ref ? : 0 0 0
455 } elsif ($libs{$self->{module}}->[0] eq 'GD') {
456 0 GD::Image->trueColor(1);
457 0 ▶ $self->{im} = $ref ? $self->{image} : GD::Image->new($self->{image});
Branch: 1 branch
BranchTrueFalseTotal
$ref ? : 0 0 0
458 } elsif ($libs{$self->{module}}->[0] eq 'Image::Magick') {
459 0 ▶ if ($ref) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ref) { } 0 0 0
460 0 $self->{im} = $self->{image};
461 } else {
462 0 $self->{im} = Image::Magick->new();
463 $error =
464 ($file)
465 ? $self->{im}->Read($self->{image})
466 0 ▶ : $self->{im}->BlobToImage($self->{image});
Branch: 1 branch
BranchTrueFalseTotal
$file ? : 0 0 0
467 0 ▶ $self->{im} = undef if $error;
Branch: 1 branch
BranchTrueFalseTotal
if $error 0 0 0
468 }
469 } else {
470 4 ▶ my $type = $file ? 'file' : 'data';
Branch: 1 branch
BranchTrueFalseTotal
$file ? : 4 0 4
471 4 ▶ $self->{im} = $ref ? $self->{image} : Imager->new($type => $self->{image});
Branch: 1 branch
BranchTrueFalseTotal
$ref ? : 0 4 4
472 4 ▶ $error = Imager->errstr() || '';
Condition50%1/2
'Imager'->errstr || ''
l!l
40
MC/DC0%0/1
'Imager'->errstr || ''
'Imager'->errstr
Truth table50%1/2
A
A= 'Imager'->errstr
Aresult
11
00
473 }
474  
475 4 ▶ unless ($self->{im}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"im"}) 4 0 4
476 4 ▶ carp("Cannot load ".($file ? $self->{image} : 'data')." with $self->{module}. $error");
Branch: 1 branch
BranchTrueFalseTotal
$file ? : 4 0 4
477 4 return;
478 }
479  
480 0 $self->{reduced} = $libs{$self->{module}}->[1];
481 0 $self->{pixels} = $libs{$self->{module}}->[2];
482  
483 $self->{methods} = {
484 0 average => \&_apply_average,
485 average_x => \&_apply_average,
486 median => \&_apply_median,
487 diff => \&_apply_diff,
488 log => \&_apply_log_average,
489 };
490  
491 0 return $self;
492 }
493  
494 # Helper function:
495 # Convert from binary to hexadecimal
496 #
497 # Borrowed from http://www.perlmonks.org/index.pl?node_id=644225
498 0 ▶sub b2h {
Subroutine b2h: not called CC=3 SCAR=24.8
Pod documented
499 0 my $num = shift;
500 0 my $WIDTH = 4;
501 0 my $index = length($num) - $WIDTH;
502 0 my $hex = '';
503 0 ▶ do {
Branch: 1 branch
BranchTrueFalseTotal
$index > -1 * $WIDTH and do { do { my $width = $WIDTH; if ($index < 0) { $width += $index; $index = 0; } ; my $cut_string = substr($num, $index, $width); $hex = sprintf("%X", oct "0b$cut_string") . $hex; $index -= $WIDTH } } 0 0 0
504 0 my $width = $WIDTH;
505 0 ▶ if ($index < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($index < 0) 0 0 0
506 0 $width += $index;
507 0 $index = 0;
508 }
509 0 my $cut_string = substr($num, $index, $width);
510 0 $hex = sprintf('%X', oct("0b$cut_string")) . $hex;
511 0 $index -= $WIDTH;
512 } while ($index > (-1 * $WIDTH));
513 0 return $hex;
514 }
515  
516 6 ▶sub _lib_order {qw/Imlib2 GD Imager ImageMagick/}
Subroutine _lib_order: called CC=1 SCAR=0.0
517  
518 1 ▶sub _is_64bit {
Subroutine _is_64bit: called CC=2 SCAR=7.2
519 1 ▶ $_64bit //= $Config{ivsize} >= 8;
Condition50%1/2
$_64bit //= $Image::PHash::Config{"ivsize"} >= 8
l!l
01
MC/DC0%0/1
$_64bit //= $Image::PHash::Config{"ivsize"} >= 8
$_64bit
Truth table50%1/2
A
A= $_64bit
Aresult
11
00
520 1 return $_64bit;
521 }
522  
523 # Difference in bits between two hex strings
524 # About 30% slower than using %064b directly, but this is portable to 32 bits
525 2 ▶sub diff {
Subroutine diff: called CC=5 SCAR=16.4
Pod documented
526 2 ▶ return _diff64(@_) if length($_[0]) <= 16 && ($_64bit || &_is_64bit);
Branch: 1 branch
BranchTrueFalseTotal
if length $_[0] <= 16 and $_64bit || &_is_64bit 1 1 2
Condition50%3/6
length $_[0] <= 16 and $_64bit || &_is_64bit
!ll&&!rl&&r
101
$_64bit or &_is_64bit
l!l&&r!l&&!r
010
MC/DC33%1/3
length $_[0] <= 16 and $_64bit || &_is_64bit
length $_[0] <= 16 $_64bit &_is_64bit
Truth table50%2/4
A and B or C
A= length $_[0] <= 16B= $_64bitC= &_is_64bit
ABCresult
0XX0
1000
11X1
1011
527 1 my $diff;
528 1 ▶ for (my $i = 0; $i < length($_[0]); $i += 8) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < length $_[0]) 3 1 4
529 3 my $d =
530 sprintf("%032b", hex(substr($_[0], $i, 8))) ^
531 sprintf("%032b", hex(substr($_[1], $i, 8)));
532 3 $diff += $d =~ tr/\0//c;
533 }
534 1 return $diff;
535 }
536  
537 1 ▶sub _diff64 {
Subroutine _diff64: called CC=1 SCAR=0.0
538 1 my $k = sprintf("%064b", hex($_[0]));
539 1 my $l = sprintf("%064b", hex($_[1]));
540 1 my $diff = $k ^ $l;
541 1 my $num_mismatch = $diff =~ tr/\0//c;
542 1 return $num_mismatch;
543 }
544  
545 # Reduce the size of an image using Imlib2
546 0 ▶sub _reduce_Imlib2 {
Subroutine _reduce_Imlib2: not called CC=3 SCAR=24.8
547 0 my $self = shift;
548 return $self->{im_scaled} = $self->{im}
549 if $self->{im}->width == $self->{dct_size}
550 0 ▶ && $self->{im}->height == $self->{dct_size};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"im"}->width == $self->{"dct_size"} and $self->{"im"}->height == $self->{"dct_size"} 0 0 0
Condition0%0/3
$self->{"im"}->width == $self->{"dct_size"} and $self->{"im"}->height == $self->{"dct_size"}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"im"}->width == $self->{"dct_size"} and $self->{"im"}->height == $self->{"dct_size"}
$self->{"im"}->width == $self->{"dct_size"} $self->{"im"}->height == $self->{"dct_size"}
Truth table0%0/3
A and B
A= $self->{"im"}->width == $self->{"dct_size"}B= $self->{"im"}->height == $self->{"dct_size"}
ABresult
0X0
100
111
551  
552 $self->{im_scaled} =
553 0 $self->{im}->create_scaled_image($self->{dct_size}, $self->{dct_size});
554 }
555  
556 # Reduce the size of an image using GD
557 0 ▶sub _reduce_GD {
Subroutine _reduce_GD: not called CC=3 SCAR=24.8
558 0 my $self = shift;
559 0 $self->{im_scaled} = $self->{im};
560 return
561 if $self->{im}->width == $self->{dct_size}
562 0 ▶ && $self->{im}->height == $self->{dct_size};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"im"}->width == $self->{"dct_size"} and $self->{"im"}->height == $self->{"dct_size"} 0 0 0
Condition0%0/3
$self->{"im"}->width == $self->{"dct_size"} and $self->{"im"}->height == $self->{"dct_size"}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"im"}->width == $self->{"dct_size"} and $self->{"im"}->height == $self->{"dct_size"}
$self->{"im"}->width == $self->{"dct_size"} $self->{"im"}->height == $self->{"dct_size"}
Truth table0%0/3
A and B
A= $self->{"im"}->width == $self->{"dct_size"}B= $self->{"im"}->height == $self->{"dct_size"}
ABresult
0X0
100
111
563  
564 0 my $dest = GD::Image->new($self->{dct_size}, $self->{dct_size});
565  
566 $dest->copyResampled(
567 $self->{im_scaled}, 0, 0, # (srcimg, dstX, dstY)
568 0, 0, $self->{dct_size}, $self->{dct_size}, # (srcX, srxY, destX, destY)
569 $self->{im_scaled}->width, $self->{im_scaled}->height
570 0 );
571 0 $self->{im_scaled} = $dest;
572 }
573  
574 # Reduce the size of an image using Image::Magick
575 0 ▶sub _reduce_Magick {
Subroutine _reduce_Magick: not called CC=3 SCAR=24.8
576 0 my $self = shift;
577 0 $self->{im_scaled} = $self->{im};
578
579 0 my ($w, $h) = $self->{im}->Get('width', 'height');
580 0 ▶ return if $w == $self->{dct_size} && $h == $self->{dct_size};
Branch: 1 branch
BranchTrueFalseTotal
if $w == $self->{"dct_size"} and $h == $self->{"dct_size"} 0 0 0
Condition0%0/3
$w == $self->{"dct_size"} and $h == $self->{"dct_size"}
!ll&&!rl&&r
000
MC/DC0%0/2
$w == $self->{"dct_size"} and $h == $self->{"dct_size"}
$w == $self->{"dct_size"} $h == $self->{"dct_size"}
Truth table0%0/3
A and B
A= $w == $self->{"dct_size"}B= $h == $self->{"dct_size"}
ABresult
0X0
100
111
581  
582 0 $self->{im_scaled}->Set(antialias => 'True');
583 $self->{im_scaled}->Resize(
584 width => $self->{dct_size},
585 height => $self->{dct_size},
586 filter => $self->{magick_filter}
587 0 );
588 }
589  
590 # Reduce the size of an image using Imager
591 0 ▶sub _reduce_Imager {
Subroutine _reduce_Imager: not called CC=3 SCAR=24.8
592 0 my $self = shift;
593 return $self->{im_scaled} = $self->{im}
594 if $self->{im}->getwidth() == $self->{dct_size}
595 0 ▶ && $self->{im}->getheight() == $self->{dct_size};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"im"}->getwidth == $self->{"dct_size"} and $self->{"im"}->getheight == $self->{"dct_size"} 0 0 0
Condition0%0/3
$self->{"im"}->getwidth == $self->{"dct_size"} and $self->{"im"}->getheight == $self->{"dct_size"}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"im"}->getwidth == $self->{"dct_size"} and $self->{"im"}->getheight == $self->{"dct_size"}
$self->{"im"}->getwidth == $self->{"dct_size"} $self->{"im"}->getheight == $self->{"dct_size"}
Truth table0%0/3
A and B
A= $self->{"im"}->getwidth == $self->{"dct_size"}B= $self->{"im"}->getheight == $self->{"dct_size"}
ABresult
0X0
100
111
596  
597 $self->{im_scaled} = $self->{im}->scale(
598 xpixels => $self->{dct_size},
599 ypixels => $self->{dct_size},
600 qtype => $self->{imager_qtype},
601 0 type => "nonprop"
602 );
603 }
604  
605 # Return the pixel values for an image when using Imlib2
606 0 ▶sub _pixels_Imlib2 {
Subroutine _pixels_Imlib2: not called CC=3 SCAR=24.8
607 0 my $self = shift;
608 0 my @pixels;
609 0 ▶ for (my $y = 0; $y < $self->{dct_size}; $y++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($y < $self->{"dct_size"}) 0 0 0
610 0 ▶ for (my $x = 0; $x < $self->{dct_size}; $x++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($x < $self->{"dct_size"}) 0 0 0
611  
612 0 my ($red, $green, $blue, $a) = $self->{im_scaled}->query_pixel($x, $y);
613 0 my $grey = $red * 0.3 + $green * 0.59 + $blue * 0.11;
614 0 push(@pixels, $grey);
615 }
616 }
617  
618 0 return \@pixels;
619 }
620  
621 # Return the pixel values for an image when using GD
622 0 ▶sub _pixels_GD {
Subroutine _pixels_GD: not called CC=3 SCAR=24.8
623 0 my $self = shift;
624 0 my @pixels;
625 0 ▶ for (my $y = 0; $y < $self->{dct_size}; $y++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($y < $self->{"dct_size"}) 0 0 0
626 0 ▶ for (my $x = 0; $x < $self->{dct_size}; $x++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($x < $self->{"dct_size"}) 0 0 0
627  
628 0 my $color = $self->{im_scaled}->getPixel($x, $y);
629 0 my ($red, $green, $blue) = $self->{im_scaled}->rgb($color);
630 0 my $grey = $red * 0.3 + $green * 0.59 + $blue * 0.11;
631 0 push(@pixels, $grey);
632 }
633 }
634  
635 0 return \@pixels;
636 }
637  
638 # Return the pixel values for an image when using Image::Magick
639 0 ▶sub _pixels_Magick {
Subroutine _pixels_Magick: not called CC=4 SCAR=30.0
640 0 my $self = shift;
641 0 my @pixels;
642 0 ▶ for (my $y = 0; $y < $self->{dct_size}; $y++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($y < $self->{"dct_size"}) 0 0 0
643 0 ▶ for (my $x = 0; $x < $self->{dct_size}; $x++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($x < $self->{"dct_size"}) 0 0 0
644 my @pixel = $self->{im_scaled}->GetPixel(
645 0 x => $x,
646 y => $y,
647 normalize => 0
648 );
649 0 my $grey = $pixel[0] * 0.3 + $pixel[1] * 0.59 + $pixel[2] * 0.11;
650 0 push(@pixels, $grey);
651 }
652 }
653  
654 0 ▶ for (my $i = 0; $i <= $#pixels; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i <= $#pixels) 0 0 0
655 0 $pixels[$i] = $pixels[$i] / 256;
656 }
657  
658 0 return \@pixels;
659 }
660  
661 # Return the pixel values for an image when using Imager
662 0 ▶sub _pixels_Imager {
Subroutine _pixels_Imager: not called CC=3 SCAR=24.8
663 0 my $self = shift;
664 0 my @pixels;
665 0 ▶ for (my $y = 0; $y < $self->{dct_size}; $y++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($y < $self->{"dct_size"}) 0 0 0
666 0 ▶ for (my $x = 0; $x < $self->{dct_size}; $x++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($x < $self->{"dct_size"}) 0 0 0
667 my $c = $self->{im_scaled}->getpixel(
668 0 x => $x,
669 y => $y
670 );
671 0 my ($red, $green, $blue, $alpha) = $c->rgba();
672 0 my $grey = $red * 0.3 + $green * 0.59 + $blue * 0.11;
673 0 push(@pixels, $grey);
674 }
675 }
676 0 return \@pixels;
677 }
678  
679 0 ▶sub reducedimage {
Subroutine reducedimage: not called CC=2 SCAR=17.9
Pod documented
680 0 my ($self, %opt) = @_;
681  
682 0 ▶ $self->{reduced}->($self, %opt) unless $self->{im_scaled};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"im_scaled"} 0 0 0
683 0 return $self->{im_scaled};
684 }
685  
686 0 ▶sub dctdump {
Subroutine dctdump: not called CC=3 SCAR=24.8
Pod documented
687 0 my ($self, %opt) = @_;
688  
689 0 ▶ $self->{reduced}->($self, %opt) unless $self->{im_scaled};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"im_scaled"} 0 0 0
690 0 ▶ $self->{dct} ||= dct2d($self->{pixels}->(($self, %opt)));
Condition0%0/3
$self->{"dct"} ||= dct2d($self->{"pixels"}->(($self, %opt)))
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"dct"} ||= dct2d($self->{"pixels"}->(($self, %opt)))
$self->{"dct"} dct2d($self->{"pixels"}->(($self, %opt)))
Truth table0%0/3
A ||= B
A= $self->{"dct"}B= dct2d($self->{"pixels"}->(($self, %opt)))
ABresult
1X1
011
000
691 0 my $dctv = $self->_mirroring(%opt);
692  
693 0 return $self->{$dctv};
694 }
695  
696 0 ▶sub printbitmatrix {
Subroutine printbitmatrix: not called CC=14 SCAR=53.5
Pod documented
697 0 my $self = shift;
698 0 my %opt = $self->_validate_options(@_);
699 0 my @array = $self->pHash(%opt);
700 0 ▶ my $sep = $opt{separator} || '';
Condition0%0/2
$opt{'separator'} || ''
l!l
00
MC/DC0%0/1
$opt{'separator'} || ''
$opt{'separator'}
Truth table0%0/2
A
A= $opt{'separator'}
Aresult
11
00
701 0 ▶ my $fill = $opt{filler} || ' ';
Condition0%0/2
$opt{'filler'} || ' '
l!l
00
MC/DC0%0/1
$opt{'filler'} || ' '
$opt{'filler'}
Truth table0%0/2
A
A= $opt{'filler'}
Aresult
11
00
702  
703 0 my ($xs, $ys) = split(/x/, $opt{geometry});
704 0 my $str = '';
705 0 ▶ if ($ys) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ys) { } 0 0 0
706 0 ▶ for (my $i = 0; $i < $xs; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $xs) 0 0 0
707 $str .= $opt{reduce} && ($i+$_==0 || $i+$_ >= ($xs+$ys)/2) ? "$fill$sep" : shift(@array).$sep
708 0 ▶ for (0..$ys-1);
Branch: 1 branch
BranchTrueFalseTotal
$opt{'reduce'} && ($i + $_ == 0 || $i + $_ >= ($xs + $ys) / 2) ? : 0 0 0
Condition0%0/6
$opt{"reduce"} and $i + $_ == 0 || $i + $_ >= ($xs + $ys) / 2
!ll&&!rl&&r
000
$i + $_ == 0 or $i + $_ >= ($xs + $ys) / 2
l!l&&r!l&&!r
000
MC/DC0%0/3
$opt{"reduce"} and $i + $_ == 0 || $i + $_ >= ($xs + $ys) / 2
$opt{"reduce"} $i + $_ == 0 $i + $_ >= ($xs + $ys) / 2
Truth table0%0/4
A and B or C
A= $opt{"reduce"}B= $i + $_ == 0C= $i + $_ >= ($xs + $ys) / 2
ABCresult
0XX0
1000
11X1
1011
709 0 $str .= "\n";
710 }
711 } else {
712 0 my @matrix = ("$fill$sep");
713 OUTER:
714 0 ▶ for (my $i = 1; $i < $self->{dct_size}; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $self->{"dct_size"}) 0 0 0
715 0 ▶ for (my $j = 0; $j <= $i; $j++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j <= $i) 0 0 0
716 0 ▶ $matrix[$j] //= '';
Condition0%0/2
$matrix[$j] //= ""
l!l
00
MC/DC0%0/1
$matrix[$j] //= ""
$matrix[$j]
Truth table0%0/2
A
A= $matrix[$j]
Aresult
11
00
717 0 $matrix[$j] .= shift(@array).$sep;
718 0 ▶ last OUTER unless @array;
Branch: 1 branch
BranchTrueFalseTotal
unless @array 0 0 0
719 }
720 }
721 0 $str .= "$_\n" for @matrix;
722 }
723 0 return $str;
724 }
725  
726 0 ▶sub _mirroring {
Subroutine _mirroring: not called CC=6 SCAR=37.4
727 0 my ($self, %opt) = @_;
728  
729 0 my $dctv = 'dct';
730 0 ▶ if ($opt{mirrorproof}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($opt{'mirrorproof'}) { } 0 0 0
elsif ($opt{'mirror'}) { } 0 0 0
731 0 $dctv = 'mirrorproof';
732 0 ▶ $self->{$dctv} ||= _dct_mirrorproof($self->{dct});
Condition0%0/3
$self->{$dctv} ||= _dct_mirrorproof($self->{"dct"})
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{$dctv} ||= _dct_mirrorproof($self->{"dct"})
$self->{$dctv} _dct_mirrorproof($self->{"dct"})
Truth table0%0/3
A ||= B
A= $self->{$dctv}B= _dct_mirrorproof($self->{"dct"})
ABresult
1X1
011
000
733 0 ▶ croak("Options 'mirror' and 'mirrorproof' are mutually exclusive") if $opt{mirror};
Branch: 1 branch
BranchTrueFalseTotal
if $opt{"mirror"} 0 0 0
734 } elsif ($opt{mirror}) {
735 0 $dctv = 'mirror';
736 0 ▶ $self->{$dctv} ||= _dct_mirror($self->{dct});
Condition0%0/3
$self->{$dctv} ||= _dct_mirror($self->{"dct"})
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{$dctv} ||= _dct_mirror($self->{"dct"})
$self->{$dctv} _dct_mirror($self->{"dct"})
Truth table0%0/3
A ||= B
A= $self->{$dctv}B= _dct_mirror($self->{"dct"})
ABresult
1X1
011
000
737 }
738 0 return $dctv;
739 }
740  
741 0 ▶sub _validate_options {
Subroutine _validate_options: not called CC=9 SCAR=45.0
742 0 my ($self, %opt) = @_;
743 0 my %valid = (
744 geometry => 1,
745 method => 1,
746 mirror => 1,
747 mirrorproof => 1,
748 reduce => 1,
749 separator => 1,
750 filler => 1
751 );
752  
753 0 foreach (keys %opt) {
754 0 ▶ carp("Unknown option '$_'") unless $valid{$_};
Branch: 1 branch
BranchTrueFalseTotal
unless $valid{$_} 0 0 0
755 }
756  
757 0 ▶ $opt{geometry} ||= '8x8';
Condition0%0/2
$opt{"geometry"} ||= "8x8"
l!l
00
MC/DC0%0/1
$opt{"geometry"} ||= "8x8"
$opt{"geometry"}
Truth table0%0/2
A
A= $opt{"geometry"}
Aresult
11
00
758 0 ▶ $opt{method} ||= 'average';
Condition0%0/2
$opt{"method"} ||= "average"
l!l
00
MC/DC0%0/1
$opt{"method"} ||= "average"
$opt{"method"}
Truth table0%0/2
A
A= $opt{"method"}
Aresult
11
00
759 0 ▶ if ($opt{geometry} =~ /^(\d+)(x\1)?$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt{'geometry'} =~ /^(\d+)(x\1)?$/) { } 0 0 0
760 croak("geometry cannot be greater than the resize value ($self->{dct_size})")
761 0 ▶ if $2 && $1 > $self->{dct_size};
Branch: 1 branch
BranchTrueFalseTotal
if $2 and $1 > $self->{"dct_size"} 0 0 0
Condition0%0/3
$2 and $1 > $self->{"dct_size"}
!ll&&!rl&&r
000
MC/DC0%0/2
$2 and $1 > $self->{"dct_size"}
$2 $1 > $self->{"dct_size"}
Truth table0%0/3
A and B
A= $2B= $1 > $self->{"dct_size"}
ABresult
0X0
100
111
762 } else {
763 0 croak("geometry expected to be either 'NxN' for square matrix, or number of bits");
764 }
765 0 croak("Unsupported method. Choose from: ".keys(%{$self->{methods}}))
766 0 ▶ unless $self->{methods}->{$opt{method}};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"methods"}{$opt{"method"}} 0 0 0
767  
768 0 return %opt;
769 }
770  
771 0 ▶sub pHash {
Subroutine pHash: not called CC=24 SCAR=64.0
Pod documented
772 0 my $self = shift;
773 0 my %opt = $self->_validate_options(@_);
774  
775 0 ▶ $self->{reduced}->($self, %opt) unless $self->{im_scaled};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"im_scaled"} 0 0 0
776 0 ▶ $self->{dct} ||= dct2d($self->{pixels}->($self, %opt));
Condition0%0/3
$self->{"dct"} ||= dct2d($self->{"pixels"}->($self, %opt))
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"dct"} ||= dct2d($self->{"pixels"}->($self, %opt))
$self->{"dct"} dct2d($self->{"pixels"}->($self, %opt))
Truth table0%0/3
A ||= B
A= $self->{"dct"}B= dct2d($self->{"pixels"}->($self, %opt))
ABresult
1X1
011
000
777  
778 0 my $dctv = $self->_mirroring(%opt);
779  
780 0 my (@array, @extra);
781 0 ▶ my $x_mult = ($opt{method} eq 'median' || $opt{method} eq 'average_x') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$opt{'method'} eq 'median' || $opt{'method'} eq 'average_x' ? : 0 0 0
Condition0%0/3
$opt{"method"} eq "median" or $opt{"method"} eq "average_x"
l!l&&r!l&&!r
000
MC/DC0%0/2
$opt{"method"} eq "median" or $opt{"method"} eq "average_x"
$opt{"method"} eq "median" $opt{"method"} eq "average_x"
Truth table0%0/3
A or B
A= $opt{"method"} eq "median"B= $opt{"method"} eq "average_x"
ABresult
1X1
011
000
782 0 ▶ if ($opt{geometry} =~ /x/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt{'geometry'} =~ /x/) { } 0 0 0
783 0 my ($xs, $ys) = split(/x/, $opt{geometry});
784 0 ▶ for (my $i = 0; $i < $xs; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $xs) 0 0 0
785 0 ▶ for (my $j = 0; $j < $ys; $j++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < $ys) 0 0 0
786 0 ▶ next if $opt{reduce} && $i + $j == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $opt{"reduce"} and $i + $j == 0 0 0 0
Condition0%0/3
$opt{"reduce"} and $i + $j == 0
!ll&&!rl&&r
000
MC/DC0%0/2
$opt{"reduce"} and $i + $j == 0
$opt{"reduce"} $i + $j == 0
Truth table0%0/3
A and B
A= $opt{"reduce"}B= $i + $j == 0
ABresult
0X0
100
111
787 0 ▶ if (!$opt{reduce} || ($i + $j < ($xs + $ys) / 2)) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $opt{'reduce'} or $i + $j < ($xs + $ys) / 2) { } 0 0 0
elsif ($x_mult) { } 0 0 0
Condition0%0/3
not $opt{"reduce"} or $i + $j < ($xs + $ys) / 2
l!l&&r!l&&!r
000
MC/DC0%0/2
not $opt{"reduce"} or $i + $j < ($xs + $ys) / 2
not $opt{"reduce"} $i + $j < ($xs + $ys) / 2
Truth table0%0/3
not(A) or B
A= not $opt{"reduce"}B= $i + $j < ($xs + $ys) / 2
ABresult
1X1
011
000
788 0 push @array, $self->{$dctv}->[$i * $self->{dct_size} + $j];
789 } elsif ($x_mult) {
790 0 push @extra, $self->{$dctv}->[$i * $self->{dct_size} + $j];
791 }
792 }
793 }
794 # Let's allow diff=1 for median, even for NxN matrices
795 push(@extra, $self->{$dctv}->[$xs+1], $self->{$dctv}->[($xs+1) * $self->{dct_size}])
796 0 ▶ if ($x_mult && !$opt{reduce} && $xs < $self->{dct_size});
Branch: 1 branch
BranchTrueFalseTotal
if $x_mult and not $opt{"reduce"} and $xs < $self->{"dct_size"} 0 0 0
Condition0%0/6
$x_mult and not $opt{"reduce"} and $xs < $self->{"dct_size"}
!ll&&!rl&&r
000
$x_mult and not $opt{"reduce"}
!ll&&!rl&&r
000
MC/DC0%0/3
$x_mult and not $opt{"reduce"} and $xs < $self->{"dct_size"}
$x_mult not $opt{"reduce"} $xs < $self->{"dct_size"}
Truth table0%0/4
A and not(B) and C
A= $x_multB= not $opt{"reduce"}C= $xs < $self->{"dct_size"}
ABCresult
0XX0
10X0
1100
1111
797 } else {
798 OUTER:
799 0 ▶ for (my $i = 1; $i < $self->{dct_size}; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $self->{"dct_size"}) 0 0 0
800 0 ▶ for (my $j = 0; $j <= $i; $j++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j <= $i) 0 0 0
801 0 ▶ if (scalar @array < $opt{geometry}) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @array < $opt{'geometry'}) { } 0 0 0
802 0 push(@array, $self->{$dctv}->[($i-$j)*$self->{dct_size}+$j]);
803 } else {
804 $x_mult && scalar(@extra) < $x_mult * $opt{geometry}
805 0 ▶ ? push(@extra, $self->{$dctv}->[($i - $j) * $self->{dct_size} + $j])
Branch: 1 branch
BranchTrueFalseTotal
$x_mult && scalar @extra < $x_mult * $opt{'geometry'} ? : 0 0 0
Condition0%0/3
$x_mult and scalar @extra < $x_mult * $opt{"geometry"}
!ll&&!rl&&r
000
MC/DC0%0/2
$x_mult and scalar @extra < $x_mult * $opt{"geometry"}
$x_mult scalar @extra < $x_mult * $opt{"geometry"}
Truth table0%0/3
A and B
A= $x_multB= scalar @extra < $x_mult * $opt{"geometry"}
ABresult
0X0
100
111
806 : last OUTER;
807 }
808 }
809 }
810 }
811  
812 # Convert to binary using median/average threshold
813 0 ▶ my $skip = (!$opt{reduce} && $opt{geometry} =~ /x/) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
!$opt{'reduce'} && $opt{'geometry'} =~ /x/ ? : 0 0 0
Condition0%0/3
not $opt{"reduce"} and $opt{"geometry"} =~ /x/
!ll&&!rl&&r
000
MC/DC0%0/2
not $opt{"reduce"} and $opt{"geometry"} =~ /x/
not $opt{"reduce"} $opt{"geometry"} =~ /x/
Truth table0%0/3
not(A) and B
A= not $opt{"reduce"}B= $opt{"geometry"} =~ /x/
ABresult
0X0
100
111
814 0 $self->{methods}->{$opt{method}}->(\@array, $skip, \@extra);
815  
816  
817 # Return an array of binary values in array context and a hex representative in scalar context.
818 0 ▶ if (wantarray()) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 0 0 0
819 0 return @array;
820 } else {
821 0 return b2h(join('', @array));
822 }
823 }
824  
825 0 ▶sub _dct_mirror {
Subroutine _dct_mirror: not called CC=2 SCAR=17.9
826 0 my $dct = shift;
827 0 my $t = 1;
828 0 ▶ my @mirror = map {($t ^= 1) ? -$_ : $_} @$dct;
Branch: 1 branch
BranchTrueFalseTotal
($t ^= 1) ? : 0 0 0
829 0 return \@mirror;
830 }
831  
832 0 ▶sub _dct_mirrorproof {
Subroutine _dct_mirrorproof: not called CC=2 SCAR=17.9
833 0 my $dct = shift;
834 0 my $t = 1;
835 0 ▶ my @mirror = map {($t ^= 1) ? abs($_) : $_} @$dct;
Branch: 1 branch
BranchTrueFalseTotal
($t ^= 1) ? : 0 0 0
836 0 return \@mirror;
837 }
838  
839 0 ▶sub _apply_average {
Subroutine _apply_average: not called CC=5 SCAR=34.0
840 0 my $array = shift;
841 0 my $skip = shift;
842 0 my $extra = shift;
843 0 my $average = 0;
844 0 $average += $array->[$_] foreach $skip .. $#$array;
845 0 $average += $_ foreach @$extra;
846 0 $average /= scalar(@$array) + scalar(@$extra) - $skip;
847 0 ▶ $array->[$_] = $array->[$_] >= $average ? '1' : '0' foreach 0 .. $#$array;
Branch: 1 branch
BranchTrueFalseTotal
$array->[$_] >= $average ? : 0 0 0
848 }
849  
850 0 ▶sub _apply_log_average {
Subroutine _apply_log_average: not called CC=6 SCAR=37.4
851 0 my $array = shift;
852 0 my $skip = shift;
853 0 my $exp = 1 + (scalar(@$array)**(1 / 6));
854 0 my $average = 0;
855 0 foreach ($skip .. $#$array) {
856 0 my $add = abs($array->[$_])**(1 / $exp);
857 0 ▶ $average += $array->[$_] < 0 ? -$add : $add;
Branch: 1 branch
BranchTrueFalseTotal
$array->[$_] < 0 ? : 0 0 0
858 }
859 0 $average /= scalar(@$array) - $skip;
860 0 my $thres = abs($average)**$exp;
861 0 ▶ $thres *= -1 if $average < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $average < 0 0 0 0
862 0 ▶ $array->[$_] = $array->[$_] >= $thres ? '1' : '0' foreach 0 .. $#$array;
Branch: 1 branch
BranchTrueFalseTotal
$array->[$_] >= $thres ? : 0 0 0
863 }
864  
865 0 ▶sub _apply_diff {
Subroutine _apply_diff: not called CC=3 SCAR=24.8
866 0 my $array = shift;
867 0 my $prev = 0;
868 0 foreach (0 .. $#$array) {
869 0 ▶ my $diff = $array->[$_] > $prev ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$array->[$_] > $prev ? : 0 0 0
870 0 $prev = $array->[$_];
871 0 $array->[$_] = $diff;
872 }
873 }
874  
875 0 ▶sub _apply_median {
Subroutine _apply_median: not called CC=4 SCAR=30.0
876 0 my $array = shift;
877 0 my $skip = shift;
878 0 my $extra = shift;
879 0 my @vals = sort {$a <=> $b} @$array, @$extra;
880 0 my $len = scalar @vals - $skip;
881 0 ▶ my $thresh =
Branch: 1 branch
BranchTrueFalseTotal
$len % 2 ? : 0 0 0
882 $len % 2
883 ? $vals[int($len / 2)]
884 : ($vals[int($len / 2) - 1] + $vals[int($len / 2)]) / 2;
885 0 ▶ $array->[$_] = $array->[$_] >= $thresh ? '1' : '0' foreach 0 .. $#$array;
Branch: 1 branch
BranchTrueFalseTotal
$array->[$_] >= $thresh ? : 0 0 0
886 }
887  
888 =head1 ACKNOWLEDGEMENTS
889  
890 Initially based on L<Image::Hash>, so some code to do with loading images, pixels
891 etc has been kept/adapted.
892  
893 =head1 AUTHOR
894  
895 Dimitrios Kechagias, C<< <dkechag at cpan.org> >>
896
897 =head1 BUGS
898  
899 Please report any bugs or feature requests either on GitHub, or on RT (via the email
900 C<bug-image-phash at rt.cpan.org> or web interface at L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Image-PHash>).
901  
902 I will be notified, and then you'll be notified of progress on your bug as I make changes.
903  
904 =head1 GIT
905  
906 L<https://github.com/dkechag/Image-PHash>
907
908 =head1 COPYRIGHT & LICENSE
909  
910 Copyright (C) 2022, SpareRoom & Dimitrios Kechagias.
911  
912 This program is free software; you can redistribute
913 it and/or modify it under the same terms as Perl itself.
914  
915 =cut
916  
917  
918 5 1;
↑ Summary