blib/lib/Image/PHash.pm

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