lib/PDL/IO/Dcm.pm

filter: Statementstmt 12.5% 42 / 335 Branchbran 0.7% 1 / 126 Conditioncond 0.0% 0 / 10 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 48.1% 13 / 27 Podpod 100% 11 / 11 totaltotal 13.0% 67 / 515 CC 95 SCAR 54.5
CC
95
Cov
9%
load_dcm_dir
650.0
parse_dcms
380.0
printStruct
156.0
CRAP 233.7
« lib/PDL/IO/Dcm/Plugins/MRISiemens.pm ↑ Summary lib/PDL/IO/Dcm/Plugins/Primitive.pm »
1 #!/usr/bin/perl
2 #
3 package PDL::IO::Dcm;
4  
5  
6 2 our $VERSION = '1.011';
7  
8  
9 2 ▶use PDL;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 #use PDL::NiceSlice;
11 2 ▶use List::Util qw/first /;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 #use List::MoreUtils; # qw{any};
13 #use Data::Dumper;
14 #use PDL::IO::Dumper;
15 2 ▶use DicomPack::IO::DicomReader;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 2 ▶use Storable qw/dclone/;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 2 ▶use DicomPack::DB::DicomTagDict qw/getTag getTagDesc/;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 2 ▶use DicomPack::DB::DicomVRDict qw/getVR/;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 2 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 #use PDL::IO::Nifti;
21 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 #use PDL::IO::Sereal;
23 #use 5.10.0;
24  
25 2 our @ISA=qw/Exporter/;
26 2 our @EXPORT_OK=qw/read_dcm parse_dcms load_dcm_dir printStruct/;
27  
28 2 my $plugin_dir="PDL::IO::Dcm::Plugins::";
29  
30  
31 0 ▶sub sort_series {
Subroutine sort_series: not called CC=1 SCAR=6.9
Pod documented
32 0 my $ret=$_[0]->hdr->{dicom}->{"Series Number"};
33 0 $ret=~ s/^\s+|\s+$//g; $ret;
34 }
35  
36 # copied and modified from stackoverflow or perlmonks thread (can't remember atm)
37 0 ▶sub printStruct {
Subroutine printStruct: not called CC=12 SCAR=50.5
Pod documented
38 0 my ($struct,$structName,$pre)=@_;
39 # print "-----------------\n" unless (defined($pre));
40 #
41 0 my $res;
42 #if (!ref($struct)){ # $struct is a scalar.
43 0 ▶ if (ref($struct) eq "ARRAY") { # Struct is an array reference
Branch: 3 branches
BranchTrueFalseTotal
if (ref $struct eq 'ARRAY') { } 0 0 0
elsif (ref $struct eq 'HASH') { } 0 0 0
elsif (ref $struct eq 'PDL') { } 0 0 0
44 #return ("ARRAY(".scalar(@$struct).")") if (@$struct>100);
45 0 ▶ for(my$i=0;$i<@$struct;$i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @$struct) 0 0 0
46 0 ▶ if (ref($struct->[$i]) eq "HASH") {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $struct->[$i] eq 'HASH') { } 0 0 0
elsif (ref $struct->[$i] eq 'ARRAY') { } 0 0 0
elsif (ref $struct->[$i] eq 'PDL') { } 0 0 0
47 0 $res.=printStruct($struct->[$i],$structName."->[$i]",$pre." ");
48 } elsif (ref($struct->[$i]) eq "ARRAY") { # contents of struct is array ref
49 #$res.= "$strucItName->"."[$i]: ()\n" if (@{$struct->[$i]}==0);
50 0 my $string = printStruct($struct->[$i],$structName."->[$i]",$pre." ");
51 0 $res.=$string;
52 #$res.= "$structName->"."[$i]: $string\n" if ($string);
53 } elsif (ref($struct->[$i]) eq "PDL") { # contents of struct is array ref
54 0 $res.= "$structName->"."[$i]: ".(join (' ',list ($struct->[$i])))."\n";
55 } else { # contents of struct is a scalar, just print it.
56
57 0 $res.= "$structName->"."[$i]: $struct->[$i]\n";
58 }
59 }
60 #return($res);
61 } elsif (ref($struct) eq "HASH"){ # $struct is a hash reference or a scalar
62 0 foreach (sort keys %{$struct}) {
63 0 ▶ if (ref($struct->{$_}) eq "HASH") {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $struct->{$_} eq 'HASH') { } 0 0 0
elsif (ref $struct->{$_} eq 'ARRAY') { } 0 0 0
elsif (ref $struct->{$_} eq 'PDL') { } 0 0 0
64 0 $res.=printStruct($struct->{$_},$structName."->{$_}",$pre." ");
65 } elsif (ref($struct->{$_}) eq "ARRAY") { # contents of struct is array ref
66 0 my $string = printStruct($struct->{$_},$structName."->{$_}",$pre." ");
67 0 $res.=$string;
68 #$res.= "$structName->"."{$_}: $string\n" if ($string);
69 } elsif (ref($struct->{$_}) eq "PDL") { # contents of struct is array ref
70 0 $res.= "$structName->"."{$_}: ".(join (' ',list($struct->{$_})))."\n";
71 } else { # contents of struct is a scalar, just print it.
72 0 $res.= "$structName->"."{$_}: $struct->{$_}\n";
73 }
74 }
75 #return($res);
76 } elsif (ref ($struct) eq 'PDL') {
77 0 $res.= "$structName: ".(join (' ',list($struct)))."\n";
78 } else {
79 0 $res.= "$structName: $struct\n";
80 }
81 #print "------------------\n" unless (defined($pre));
82 0 return($res);
83 }
84  
85 0 ▶sub unpack_field{
Subroutine unpack_field: not called CC=9 SCAR=45.0
Pod documented
86 # recursive parsing of dicom fields down to scalar level.
87 0 my $id=shift;
88 0 my $tag=shift;
89 0 my $packstring;
90 0 my $value=shift;
91 0 my $return; #=shift;
92 0 ▶ if (ref($value) eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $value eq 'ARRAY') { } 0 0 0
elsif (ref $value eq 'HASH') { } 0 0 0
93 0 my @vs=();
94 0 for my $n ($#$value) {
95 0 push @vs,unpack_field ("$id/$n",getTag("$id/$n"),$$value[$n],$return);
96 }
97 0 $return=\@vs;
98 } elsif (ref ($value) eq 'HASH') {
99 0 my %vh=();
100 0 for my $v (keys %$value) {
101 0 $vh{$v}=unpack_field("$id/$v",getTag("$id/$v"),$$value{$v},$return);
102 }
103 0 $return=\%vh;
104 } else { # a scalar
105 0 my $vr=substr($value,0,2);
106 0 ▶ if ($vr eq 'XX' and defined $tag) {
Branch: 1 branch
BranchTrueFalseTotal
if ($vr eq "XX" and defined $tag) 0 0 0
Condition0%0/3
$vr eq "XX" and defined $tag
!ll&&!rl&&r
000
MC/DC0%0/2
$vr eq "XX" and defined $tag
$vr eq "XX" defined $tag
Truth table0%0/3
A and B
A= $vr eq "XX"B= defined $tag
ABresult
0X0
100
111
107 0 ($vr)=keys %{DicomPack::DB::DicomTagDict::getTag($id)->{vr}};
108 }
109 0 ▶ if ($vr eq 'TM' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($vr eq 'TM') { } 0 0 0
110 0 ($return=sprintf('%13.6f',substr($value,3,)))
111 0 =~s/^(\d\d)(\d\d)(\d\d\.\d+$)/3600*$1+60*$2+$3/e;
112 } else {
113 0 ▶ $packstring=join ('',(eval {getVR($vr)->{type}}||'a').'*');
Condition0%0/2
eval { do { getVR($vr)->{'type'} } } || 'a'
l!l
00
MC/DC0%0/1
eval { do { getVR($vr)->{'type'} } } || 'a'
eval { do { getVR($vr)->{'type'} } }
Truth table0%0/2
A
A= eval { do { getVR($vr)->{'type'} } }
Aresult
11
00
114 0 $return=unpack ($packstring,substr($value,3,));
115 }
116 }
117 0 $return;
118 }
119  
120 0 ▶sub read_dcm {
Subroutine read_dcm: not called CC=8 SCAR=42.8
Pod documented
121 0 my $file=shift;
122 0 my $opt=shift; #options
123 0 ▶ my $dcm=DicomPack::IO::DicomReader->new($file) || return;
Condition0%0/2
'DicomPack::IO::DicomReader'->new($file) || (return)
l!l
00
MC/DC0%0/1
'DicomPack::IO::DicomReader'->new($file) || (return)
'DicomPack::IO::DicomReader'->new($file)
Truth table0%0/2
A
A= 'DicomPack::IO::DicomReader'->new($file)
Aresult
11
00
124 0 my $data=$dcm->getValue('PixelData','native');
125 0 my ($h,$w)=1;
126 0 my $pdl=PDL->null;
127 0 my $plugin=$$opt{plugin};
128 0 $pdl->hdr->{raw_dicom}=$dcm->getDicomField;
129 0 for my $id (keys %{$pdl->hdr->{raw_dicom}}) {
130 0 my $tag=getTag($id); # field tag for id, if present, store under tag
131 0 my $value=unpack_field($id,$tag,$dcm->getValue($id,'native'));
132 0 ▶ if (defined $tag) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $tag) { } 0 0 0
133 0 $pdl->hdr->{dicom}->{$tag->{desc}}=$value;
134 } else { }
135 0 $pdl->hdr->{dicom}->{$id} #=~s/([0-9a-fA-F]{4}),([0-9a-fA-F]{4})/$1_$2/r}
136 =$value;
137 } # for loop over dicom ids
138 0 ▶ unless (defined ($data)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $data) { } 0 0 0
139 0 ▶ if ($dcm->getValue('SeriesNumber') == 99) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dcm->getValue("SeriesNumber") == 99) 0 0 0
140 0 warn "Could be phoenix data \n";
141 0 return;
142 }
143 # This is not a standard dicom image, refer to plugin
144 #no PDL::NiceSlice;
145 0 $pdl=$$opt{$plugin}->{read_dcm}->($dcm,$opt,$pdl);
146 } else {
147 0 $h=unpack('S',substr ($dcm->getValue('Rows','native'),3,2));
148 0 $w=unpack('S',substr ($dcm->getValue('Columns','native'),3,2));
149 0 my $datatype= (substr($data,0,2));
150 #print "Data type $datatype \n";
151 0 ▶ if ($datatype =~/OW|XX/){
Branch: 1 branch
BranchTrueFalseTotal
if ($datatype =~ /OW|XX/) 0 0 0
152 0 $pdl.=zeroes(ushort,$w,$h) ;
153 }
154 0 $pdl->make_physical;
155 0 ${$pdl->get_dataref}=substr($data,3);
156 0 $pdl->upd_data;
157 0 $pdl->hdr->{plugin}=$plugin; # store this
158 #no PDL::NiceSlice;
159 0 $$opt{$plugin}->{parser}->($dcm,$pdl); #
160 }
161 #no PDL::NiceSlice;
162 #$$opt{$plugin}->{parser}->($dcm,$pdl,$opt);
163 # keep the raw_dicom structure?
164 0 ▶ delete $pdl->hdr->{raw_dicom} if $$opt{delete_raw};
Branch: 1 branch
BranchTrueFalseTotal
if $opt->{"delete_raw"} 0 0 0
165 0 return $pdl;
166 }
167  
168 0 ▶sub is_equal {
Subroutine is_equal: not called CC=5 SCAR=34.0
Pod documented
169 0 my $a=shift;
170 0 my $b=shift;
171 0 my $opt=shift;
172 0 ▶ return if (any ($a->shape-$b->shape)); # they have equal dimensions
Branch: 1 branch
BranchTrueFalseTotal
if any($a->shape - $b->shape) 0 0 0
173 0 ▶ return 1 if ($opt =~/d/);
Branch: 1 branch
BranchTrueFalseTotal
if $opt =~ /d/ 0 0 0
174 0 ▶ return if $a->hdr->{dicom}->{'Pixel Spacing'} ne $b->hdr->{dicom}->{'Pixel Spacing'};
Branch: 1 branch
BranchTrueFalseTotal
if $a->hdr->{"dicom"}{"Pixel Spacing"} ne $b->hdr->{"dicom"}{"Pixel Spacing"} 0 0 0
175 0 ▶ return if $a->hdr->{dicom}->{'Image Orientation (Patient)'} ne $b->hdr->{dicom}->{'Image Orientation (Patient)'};
Branch: 1 branch
BranchTrueFalseTotal
if $a->hdr->{"dicom"}{"Image Orientation (Patient)"} ne $b->hdr->{"dicom"}{"Image Orientation (Patient)"} 0 0 0
176 0 1;
177 }
178  
179 0 ▶sub load_dcm_dir {
Subroutine load_dcm_dir: not called CC=25 SCAR=64.8
Pod documented
180 0 my %dcms; #([]);
181 my @pid;
182 0 my $dname=shift;
183 0 my %dims;
184 0 my $opt=shift; # field by which to split
185 0 my $id=$$opt{$$opt{plugin}}->{id};
186 0 my $sp=$$opt{$$opt{plugin}}->{split};
187 0 my $n=0;
188 0 my %refs; # reference images for each stack
189 # loop over all files in $dir, sort them using $pid into %dcms
190 0 print "Start reading files.\n";
191 0 ▶ opendir (my $dir, $dname) ||die "cannot open directory $dname!";
Branch: 1 branch
BranchTrueFalseTotal
opendir my $dir, $dname or die "cannot open directory $dname!" 0 0 0
192 0 for my $file (readdir ($dir)) {
193 0 ▶ next unless (-f "$dname/$file"); # =~m/\.dcm$|\.IMA$/;
Branch: 1 branch
BranchTrueFalseTotal
unless -f "$dname/$file" 0 0 0
194 0 ▶ next if ( $file =~/REPORT.*\.SR$/ );
Branch: 1 branch
BranchTrueFalseTotal
if $file =~ /REPORT.*\.SR$/ 0 0 0
195 0 my $p=read_dcm("$dname/$file",$opt);
196 0 ▶ eval{$p->isa('PDL')} ||next;
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $p->isa("PDL") } } or next 0 0 0
197 0 ▶ die "No plugin \n" unless $p->hdr->{plugin};
Branch: 1 branch
BranchTrueFalseTotal
unless $p->hdr->{"plugin"} 0 0 0
198 0 $n++;
199 #no PDL::NiceSlice;
200 0 my $pid=$id->($p); # Call to subroutine reference
201 0 ▶ $dcms{$pid}={} unless ref $dcms{$pid};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $dcms{$pid} 0 0 0
202 0 my $ref =$refs{$pid};
203 0 ▶ if (defined $ref) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ref) 0 0 0
204 # do files match? Can they be stacked together?
205 0 ▶ unless ( is_equal($ref,$p )) {
Branch: 1 branch
BranchTrueFalseTotal
unless (is_equal($ref, $p)) 0 0 0
206 # This doesn't make any sense, does it?
207 0 ▶ if ( !$sp and is_equal($ref,$p->transpose,)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $sp and is_equal($ref, $p->transpose)) { } 0 0 0
Condition0%0/3
not $sp and is_equal($ref, $p->transpose)
!ll&&!rl&&r
000
MC/DC0%0/2
not $sp and is_equal($ref, $p->transpose)
not $sp is_equal($ref, $p->transpose)
Truth table0%0/3
not(A) and B
A= not $spB= is_equal($ref, $p->transpose)
ABresult
0X0
100
111
208 0 $p->hdr->{tp}=1;
209 } else {
210 0 my $flag=0;
211 0 my $n='a';
212 0 my $nid;
213 0 ▶ do {
Branch: 1 branch
BranchTrueFalseTotal
$flag or do { do { $nid = &$id($p) . $n; if (ref $dcms{$nid} eq "HASH") { foreach my $r2 (values %{$dcms{$nid};}) { $flag = is_equal($r2, $p); last unless $flag; } ; } else { $dcms{$nid} = {}; $pid = $nid; $flag = 1; } ; ++$n } } 0 0 0
214 0 $nid=$id->($p).$n;
215 0 ▶ if (ref $dcms{$nid} eq 'HASH'){ # group
Branch: 1 branch
BranchTrueFalseTotal
if (ref $dcms{$nid} eq 'HASH') { } 0 0 0
216 0 for my $r2 (values %{$dcms{$nid}}){
217 0 $flag=is_equal($r2,$p);
218 0 ▶ last unless $flag;
Branch: 1 branch
BranchTrueFalseTotal
unless $flag 0 0 0
219 }
220 } else {
221 0 $dcms{$nid}={};
222 0 $pid=$nid;
223 0 $flag=1;
224 }
225 0 $n++;
226 } until $flag;
227 0 $pid=$nid;
228 }
229 }
230 } # defined $ref
231 #use PDL::NiceSlice;
232 0 my $iced=$p->hdr->{dim_idx}->copy;
233 #print "id $pid iced $iced\n";
234 0 ▶ print "." unless ($n % 100); # progress
Branch: 1 branch
BranchTrueFalseTotal
unless $n % 100 0 0 0
235 0 ▶ unless (grep (/^$pid$/,@pid)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep /^$pid$/, @pid) 0 0 0
236 0 $dims{$pid}=zeroes(short,$iced->dims);
237 0 push @pid,$pid;
238 0 $refs{$pid}=$p;
239 }
240 # Shouldn't that be in the plugin?
241 #$iced++;
242 # I'm not sure that this is necessary, $dims{$pid} is 0
243 #print "iced $iced pid $pid dims $dims{$pid}\n";
244 0 $dims{$pid}.=$dims{$pid}*($dims{$pid}>=$iced)+$iced*($iced>$dims{$pid});
245 #print "iced $iced pid $pid dims $dims{$pid}\n";
246 #use PDL::NiceSlice;
247 0 ▶ if (ref($dcms{$pid}->{$p->hdr->{dcm_key}}) eq 'PDL') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $dcms{$pid}{$p->hdr->{"dcm_key"}} eq "PDL") 0 0 0
248 warn "This key is not unique! Probably double export $pid, ",$p->hdr->{dcm_key}
249 ,' ',$p->hdr->{dicom}->{'Series Number'}
250 0 ,' ',$p->hdr->{dicom}->{'Incstance Number'};
251 0 next;
252 }
253 0 $dcms{$pid}->{$p->hdr->{dcm_key}}=$p;
254 }
255 0 print "Done reading.\n";
256 0 for my $id (@pid) {
257 #print "Sorting out dims for $id\n";
258 0 my $ldims=$dims{$id}->copy;
259 0 my $plugin=$refs{$id}->hdr->{plugin};
260 0 ▶ die "No plugin for id $id \n" unless $plugin;
Branch: 1 branch
BranchTrueFalseTotal
unless $plugin 0 0 0
261 0 my $order=pdl($$opt{$plugin}->{dim_order});
262 0 my $test=zeroes(byte,$dims{$id}->slice($order));
263 0 my $i=0;
264 #print "Test: ",$test->info,"\n";
265 0 for my $dcm (values %{$dcms{$id}}) {
266 0 ▶ die "No plugin $id\n" unless $dcm->hdr->{plugin};
Branch: 1 branch
BranchTrueFalseTotal
unless $dcm->hdr->{"plugin"} 0 0 0
267 0 ▶ next unless eval{$dcm->isa('PDL')};
Branch: 1 branch
BranchTrueFalseTotal
unless eval { do { $dcm->isa("PDL") } } 0 0 0
268 0 $i++;
269 #print "$i: ",$dcm->hdr->{dim_idx}->($order)," ? ";
270 #print $test(list $dcm->hdr->{dim_idx}->($order)),"\n";
271 0 ▶ if (any ($test->slice(list $dcm->hdr->{dim_idx}->slice($order)-1))) {
Branch: 1 branch
BranchTrueFalseTotal
if (any($test->slice(list($dcm->hdr->{"dim_idx"}->slice($order) - 1)))) 0 0 0
272 #no PDL::NiceSlice;
273 0 $test=$$opt{$plugin}->{duplicates}->($test,$dcm,$opt);
274 #use PDL::NiceSlice;
275 #print "Duplicates detected. ",$test->info;
276 }
277 0 $test->slice(list($dcm->hdr->{dim_idx}->slice($order)-1)).=1;
278 }
279 0 $ldims->slice($order).=$test->shape->copy;
280 0 $dcms{$id}->{dims}=$ldims;
281 #print "Set dims: id $id, $dims{$id}\n";
282 #print "Dims: $dims{$id} order $order ";
283 }
284 0 \%dcms;
285 }
286  
287 0 ▶sub clump_data {
Subroutine clump_data: not called CC=2 SCAR=17.9
Pod documented
288 0 my $data=shift;
289 0 my $offset=shift; # leave
290 0 my $clumplist=shift;
291 0 for my $clump (@$clumplist) {
292 0 $data=$data->clump( map {$_+$offset} @$clump);
293 }
294 0 $data;
295 }
296  
297 0 ▶sub create_image_data {
Subroutine create_image_data: not called CC=6 SCAR=37.4
Pod documented
298 # now get the rest. The plugin has to provide the dim_order
299 # field that determines the shape of the data
300 #print "Dims: $dims order $order ";
301 #print $dims($order),"\n";
302 0 my $data_ref=shift;
303 0 my $opt=shift;
304 0 ▶ next unless (ref $$data_ref{dims} eq 'PDL');
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data_ref->{"dims"} eq "PDL" 0 0 0
305 0 my $dims = $$data_ref{dims};
306 #print "ID: $pid dims $dims transpose? \n";
307 0 ▶ die "No dims \n" unless eval {$dims->isa('PDL')};
Branch: 1 branch
BranchTrueFalseTotal
unless eval { do { $dims->isa("PDL") } } 0 0 0
308 0 ▶ die "No plugin \n" unless eval {$dims->isa('PDL')};
Branch: 1 branch
BranchTrueFalseTotal
unless eval { do { $dims->isa("PDL") } } 0 0 0
309 # get a dicom, need to exclude the dims key
310 0 ▶ my $ref=$$data_ref{first { not /^dims$/ } (keys %$data_ref)};
Subroutine __ANON__: not called CC=1 SCAR=6.9
311 0 my $x=$ref->hdr->{dicom}->{Columns};
312 0 my $y=$ref->hdr->{dicom}->{Rows};
313 0 my $order=pdl($$opt{$$opt{plugin}}->{dim_order});
314 0 ▶ barf "Dimensions are all zero " unless any $order;
Branch: 1 branch
BranchTrueFalseTotal
unless any($order) 0 0 0
315 #say "id ".$ref->hdr->{dicom}->{"Series Number"}."$dims $dims\n";
316 0 my $data;
317 0 ▶ if ($ref->hdr->{tp}) { $data=zeroes(ushort,$y,$x,0+$dims->slice($order));}
Branch: 1 branch
BranchTrueFalseTotal
if ($ref->hdr->{'tp'}) { } 0 0 0
318 0 else { $data=zeroes(ushort,$x,$y,0+$dims->slice($order));}
319 0 $data;
320 }
321  
322 0 ▶sub fill_image_data {
Subroutine fill_image_data: not called CC=9 SCAR=42.9
Pod documented
323 0 my $data=shift;
324 0 my $header=$data->hdr;
325 0 my $dcm=shift;
326 0 my $ref=shift;
327 0 my $opt=shift;
328 0 my $plugin = $ref->hdr->{plugin};
329 # Insert data. Swap x,y ?
330 2 ▶ use PDL::NiceSlice;
Subroutine BEGIN: called CC=1 SCAR=0.0
331 0 my $order=$$opt{$plugin}->{dim_order};
332 #print "dcm: ",$dcm->hdr->{dim_idx},", data ",$data->info,"\n";
333 0 ▶ if ($dcm->hdr->{tp}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dcm->hdr->{'tp'}) { } 0 0 0
334 0 $data(,,list( $dcm->hdr->{dim_idx}->($order)-1))
335 .=$dcm->transpose;}
336 0 else {$data(,,list ($dcm->hdr->{dim_idx}->($order)-1)).=$dcm;}
337 # now fill all the header data
338 0 for my $key (@{$$opt{$plugin}->{key_list}}) {
339 0 $dcm->hdr->{dicom}->{$key};
340 $header->{dicom}->{$key}->(list ($dcm->hdr->{dim_idx}->($order)-1))
341 0 .=$dcm->hdr->{dicom}->{$key};
342 }
343 # preserve original info
344 #print "IDX: ",$dcm->hdr->{dim_idx};
345 0 $header->{dim_idx}->{$dcm->hdr->{dcm_key}}=$dcm->hdr->{dim_idx};
346 $header->{dcm_key}->{join ('_',list ($dcm->hdr->{dim_idx}->($order)))}
347 0 =$dcm->hdr->{dcm_key};
348 $header->{dicom}->{'Image Orientation (Patient)'}->(,list ($dcm->hdr->{dim_idx}->($order)-1))
349 0 .=pdl (split /\\/,$dcm->hdr->{dicom}->{'Image Orientation (Patient)'});
350 #say split /\\/,$dcm->hdr->{dicom}->{'Pixel Spacing'};
351 #say $header->{dicom}->{'Pixel Spacing'}->(,list($dcm->hdr->{dim_idx}->{$order}));
352  
353 #say $header->{dicom}->{'Pixel Spacing'};
354 $header->{dicom}->{'Pixel Spacing'}->(,list $dcm->hdr->{dim_idx}->($order)-1)
355 0 .=pdl (split /\\/,$dcm->hdr->{dicom}->{'Pixel Spacing'});
356 $header->{dicom}->{'Image Position (Patient)'}->(,list $dcm->hdr->{dim_idx}->($order)-1)
357 0 .=pdl (split /\\/,$dcm->hdr->{dicom}->{'Image Position (Patient)'});
358 0 for my $field (keys %{$dcm->hdr->{dicom}}) {
359 0 ▶ if ($dcm->hdr->{dicom}->{$field} ne $ref->hdr->{dicom}->{$field}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dcm->hdr->{"dicom"}{$field} ne $ref->hdr->{"dicom"}{$field}) 0 0 0
360 $header->{diff}->{$field}={}
361 0 ▶ unless ref ($header->{diff}->{$field});
Branch: 1 branch
BranchTrueFalseTotal
unless ref $header->{"diff"}{$field} 0 0 0
362 }
363 }
364 0 for my $field (keys %{$dcm->hdr->{csa}}) {
365 0 ▶ if ($dcm->hdr->{csa}->{$field} ne $ref->hdr->{csa}->{$field}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dcm->hdr->{"csa"}{$field} ne $ref->hdr->{"csa"}{$field}) 0 0 0
366 $header->{csa_diff}->{$field}={}
367 0 ▶ unless ref ($header->{csa_diff}->{$field});
Branch: 1 branch
BranchTrueFalseTotal
unless ref $header->{"csa_diff"}{$field} 0 0 0
368 }
369 }
370 2 ▶ no PDL::NiceSlice;
Subroutine BEGIN: called CC=1 SCAR=0.0
371 }
372  
373 0 ▶sub image_parser {
Subroutine image_parser: not called CC=8 SCAR=40.3
Pod documented
374 0 my $data=shift;
375 0 my $opt=shift;
376 0 my $pid=shift;
377 0 my $ind=whichND(maxover maxover maxover ($$data{$pid})); # actually populated fields!
378 0 my $header=$$data{$pid}->gethdr;
379 0 my $plugin=$$opt{plugin};
380 2 ▶ use PDL::NiceSlice;
Subroutine BEGIN: called CC=1 SCAR=0.0
381 0 ▶ if (any $ind ) {
Branch: 1 branch
BranchTrueFalseTotal
if (any($ind)) 0 0 0
382 #say $header->{dicom}->{'Pixel Spacing'}->info;
383 0 for my $ax (0..$ind->dim(0)-1) {
384 #say "Axis $ax, ",$ind($ax;-);
385 0 $$data{$pid}=$$data{$pid}->dice_axis($ax+3,$ind($ax;-)->uniq); # compact the data!
386 $header->{dicom}->{'Image Position (Patient)'}
387 0 =$header->{dicom}->{'Image Position (Patient)'}->dice_axis($ax+2,$ind($ax)->uniq);
388 $header->{dicom}->{'Image Orientation (Patient)'}
389 0 =$header->{dicom}->{'Image Orientation (Patient)'}->dice_axis($ax+2,$ind($ax)->uniq);
390 #say $header->{dicom}->{'Pixel Spacing'}->info;
391 #say "$ax+1 ",$ind($ax)->uniq;
392 0 $header->{dicom}->{'Pixel Spacing'}=$header->{dicom}->{'Pixel Spacing'}->dice_axis($ax+2,$ind($ax)->uniq);
393 0 for my $key (@{$$opt{$$opt{plugin}}->{key_list}}) {
394 #next unless chomp $key;
395 #say "key $key $ax, ",$ind($ax);
396 0 $header->{dicom}->{$key}=$header->{dicom}->{$key}->dice_axis($ax+1,$ind($ax)->uniq);
397 }
398 0 for my $val (values %{$header->{diff}}) {
399 0 ▶ $val=$val->dice_axis($ax+1,$ind($ax)->uniq) if (ref ($val) =~ /PDL/);
Branch: 1 branch
BranchTrueFalseTotal
if ref($val) =~ /PDL/ 0 0 0
400 }
401 0 for my $val (values %{$header->{csa_diff}}) {
402 0 ▶ $val=$val->dice_axis($ax+1,$ind($ax)->uniq) if (ref ($val) =~ /PDL/);
Branch: 1 branch
BranchTrueFalseTotal
if ref($val) =~ /PDL/ 0 0 0
403 }
404 }
405 }
406 #say "Data set $pid, dims $ind ", $$data{$pid}->info;
407 #say "done.";
408 $header->{dicom}->{'Image Position (Patient)'}
409 0 =clump_data($header->{dicom}->{'Image Position (Patient)'},1,$$opt{$plugin}->{clump_dims});
410 $header->{dicom}->{'Image Orientation (Patient)'}
411 0 =clump_data($header->{dicom}->{'Image Orientation (Patient)'},0,$$opt{$plugin}->{clump_dims});
412 #say $header->{dicom}->{'Pixel Spacing'};
413 $header->{dicom}->{'Pixel Spacing'}
414 0 =clump_data($header->{dicom}->{'Pixel Spacing'},0,$$opt{$plugin}->{clump_dims});
415 0 $$data{$pid}->sethdr($header);
416 2 ▶ no PDL::NiceSlice;
Subroutine BEGIN: called CC=1 SCAR=0.0
417 }
418  
419 # a lot of this has to go into plugins
420 0 ▶sub parse_dcms {
Subroutine parse_dcms: not called CC=19 SCAR=59.4
Pod documented
421 0 my %dcms=%{shift()}; # reference to hash of
422 0 my %data;
423 0 my $opt=shift;
424 # loop over all Series, pid is the series unique id
425 0 for my $pid (sort keys %dcms) {
426 0 my %stack=%{$dcms{$pid}}; # stack contains all data of one dicom series
427 #next unless $pid;
428 # first in stack serves as reference
429 0 ▶ my $ref=$stack{first { not /^dims$/} (keys %stack)};
Subroutine __ANON__: not called CC=1 SCAR=6.9
430 # let the plugin create the data structure
431 0 my $plugin=$ref->hdr->{plugin};
432 #no PDL::NiceSlice;
433 0 my $header;
434 #print "pid $pid plugin $plugin, ",$$opt{$plugin}->{create_data},"\n";
435 0 ($data{$pid},$header)=$$opt{$plugin}->{create_data}->(\%stack,$opt);
436 0 delete $stack{dims};
437 0 $data{$pid}->sethdr($header);
438 # parse the individual dicom instances
439 0 for my $dcm (values %stack) {
440 0 $$opt{$plugin}->{fill_data}->($data{$pid},$dcm,$ref,$opt);
441 0 for my $field (keys %{$dcm->hdr->{csa}}) {
442 0 ▶ if ($dcm->hdr->{csa}->{$field} ne $ref->hdr->{csa}->{$field}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dcm->hdr->{"csa"}{$field} ne $ref->hdr->{"csa"}{$field}) 0 0 0
443 $header->{csa_diff}->{$field}={}
444 0 ▶ unless ref ($header->{csa_diff}->{$field});
Branch: 1 branch
BranchTrueFalseTotal
unless ref $header->{"csa_diff"}{$field} 0 0 0
445 }
446 }
447 0 for my $field (keys %{$dcm->hdr->{dicom}}) {
448 0 ▶ if ($dcm->hdr->{dicom}->{$field} ne $ref->hdr->{dicom}->{$field}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dcm->hdr->{"dicom"}{$field} ne $ref->hdr->{"dicom"}{$field}) 0 0 0
449 $header->{diff}->{$field}={}
450 0 ▶ unless ref ($header->{diff}->{$field});
Branch: 1 branch
BranchTrueFalseTotal
unless ref $header->{"diff"}{$field} 0 0 0
451 }
452 }
453 } # for ... values %stack
454 0 $$opt{$plugin}->{image_parser}->(\%data,$opt,$pid);
455 0 for my $dcm (values %stack) {
456 0 for my $field (keys %{$header->{csa_diff}}) {
457 $header->{csa_diff}->{$field}->{$dcm->hdr->{dcm_key}}=
458 0 $dcm->hdr->{csa}->{$field};
459 }
460 0 for my $field (keys %{$header->{diff}}) {
461 $header->{diff}->{$field}->{$dcm->hdr->{dcm_key}}=
462 0 $dcm->hdr->{dicom}->{$field};
463 }
464 }
465  
466 0 for my $key (@{$$opt{$plugin}->{key_list}}) {
467 #next unless chomp($key);
468 0 $header->{dicom}->{$key}=clump_data($header->{dicom}->{$key},0,$$opt{$plugin}->{clump_dims});
469 }
470 0 for my $val (values %{$header->{csa_diff}}) {
471 0 ▶ $val=clump_data($val,0,$$opt{$plugin}->{clump_dims}) if (ref ($val) =~ /PDL/);
Branch: 1 branch
BranchTrueFalseTotal
if ref($val) =~ /PDL/ 0 0 0
472 }
473 0 for my $val (values %{$header->{diff}}) {
474 0 ▶ $val=clump_data($val,0,$$opt{$plugin}->{clump_dims}) if (ref ($val) =~ /PDL/);
Branch: 1 branch
BranchTrueFalseTotal
if ref($val) =~ /PDL/ 0 0 0
475 }
476 0 $data{$pid}=clump_data($data{$pid},2,$$opt{$plugin}->{clump_dims});
477 0 die "Dimensions don't add up! @{$$opt{Dimensions}}, $#{$$opt{$plugin}->{Dimensions}} ",
478 0 ▶ $data{$pid}->info if ($data{$pid}->ndims != $#{$$opt{$plugin}->{Dimensions}}+1);
Branch: 1 branch
BranchTrueFalseTotal
if $data{$pid}->ndims != $#{$$opt{$plugin}{"Dimensions"};} + 1 0 0 0
479 #print "cloing $pid\n";
480 0 for my $key (keys %{$header->{dicom}}) {
481 #say "key $key";
482 #say sdump ($$header{dicom}->{$key});
483 #dclone($$header{$key});
484 }
485 0 $data{$pid}->sethdr(dclone($header));
486 } # for my $pid ...
487 0 \%data;
488 }
489  
490  
491  
492 2 ▶BEGIN {
Subroutine BEGIN: called CC=2 SCAR=12.4
493 2 ▶ if ($_[0] eq q/-d/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_[0] eq "-d") 0 2 2
494 0 require Carp;
495 0 ▶ $SIG{__DIE__} = sub {print Carp::longmess(@_); die;};
Subroutine __ANON__: not called CC=1 SCAR=6.9
496 }
497 }
498 2 1;
499  
500 =head1 NAME
501  
502 PDL::IO::Dcm - Reads dicom files, sorts them and stores the result into piddles with headers
503  
504 =head1 SYNOPSIS
505  
506 This module is inteded to read and sort dicom images created by medical imaging devices.
507 Either use something like the following from within your module/application
508  
509 use PDL::IO::Dcm::Plugins::Primitive qw/setup_dcm/;
510 my %options=();
511 ...
512 setup_dcm(\%options);
513 # loads all dicom files in this directory
514 my $dcms=load_dcm_dir($dir,\%options);
515 die "no data!" unless (keys %$dcms);
516 print "Read data; IDs: ",join ', ',keys %$dcms,"\n";
517 # sort all individual dicoms into a hash of piddles.
518 my $data=parse_dcms($dcms,\%options);
519  
520 ... # do something with your data.
521  
522 or use the read_dcm.pl script to convert dicom files in a directory to serealised
523 piddles (PDL::IO::Sereal) or NIFTI files with separate text headers (PDL::IO::Nifti).
524  
525 =head1 Plugins
526  
527 Modality/vendor specific treatment and sorting is done by plugins, to be
528 installed under the PDL::IO::Dcm::Plugins name space. Using Primitive should
529 get you started, data will be grouped based on dicom series numbers and sorted
530 by instance number. If you need something more sophisticated, take a look at
531 the MRISiemens plugin.
532  
533 This software is based on the use case of Siemens MRI data based on the
534 author's needs. Specific handling of file formats, data, header fields is moved to its
535 own plugin.
536  
537 Each plugin needs to support a etup_dcm() function that takes a reference to an options
538 hash. Important keys are:
539  
540 create_data() sets up the piddle holding the data and setes the dimensions in options' field.
541  
542 read_dcm() function should and probably will be moved to
543 vendor/modality specific plugin modules in future releases.
544  
545 =head1 Some notes on Dicom fields and how they are stored/treated
546  
547 The image data field is stored as the piddle, the other dicom elements are
548 first stored in the header under the raw_dicom key. After parsing, most fields
549 are accessible under the dicom key. The raw_dicom structure is then deleted,
550 use the delete_raw option if you want to change this.
551  
552 Keys are parsed into a hash under the dicom key using the DicomPack module(s)
553 to unpack. Piddles are created for data grouped based on the id option.
554 The header fields dcm_key and dim_idx are used for sorting datasets.
555  
556 =head1 Options
557  
558 The behaviour of the module's routines are controlled through options, stored in a hash. Your
559 plugin may add additional keys as needed. Fields in the options hash used by this module are:
560  
561 =over
562  
563 =item parser (rquired) - A function reference to a parser in the plugin. This function has to provide
564 dimensions information (dim_idx) key in the piddle header.
565  
566 =item clump_dims
567  
568 these are clumped together to reduce dimensions, required by e.g. Nifti (max. 7).
569  
570 =item delete_raw
571  
572 flag controlling whether the unparsed dicom fields under raw_dicom should be
573 retained; default no.
574  
575 =item dim_order
576  
577 order in which dimensions are stored, used to reorder the data. xy are typically
578 the first two and are often not counted.
579  
580 =item Dimensions
581  
582 list ref to names of expected dims. xy are left out. Should be set by your
583 plugin to help interpret data.
584  
585 =item duplicates
586  
587 a code ref executed if two images have identical positions in stack, e.g. same
588 Series Number Instance Number, this can happen.
589  
590 =item id
591  
592 code ref expecting to return a key to group files; defaults to \&sort_series.
593  
594 =item internal_dims
595  
596 raw dimension list before any clumping. This is not used at the moment but
597 allows for description of the input dimensions.
598  
599 =item sort
600  
601 code ref typically set to your plugin's populate_header routine. This is called
602 to set dim_idx and dcm_key for each file
603  
604 =item sp:
605  
606 Split slice groups, otherwise they are stacked together if xy-dims match, even transposed.
607  
608 =back
609  
610 =head1 SUBROUTINES/METHODS
611  
612 =head2 clump_data
613  
614 Utitlity to clump a piddle over clump_dims option field, takes an offset
615  
616 =head2 create_image_data
617  
618 to be called from create_data() for image data.
619  
620 =head2 fill_image_data
621  
622 to be called from fill_data() for image data.
623  
624 =head2 image_parser
625  
626 to be called from parser() for image data.
627  
628 =head2 is_equal ($dcm1,$dcm2,$pattern)
629  
630 This is used to check if two dicoms can be stacked based on matrix size,
631 orientation and pixel spacing.
632  
633 If $pattern matches /d/, only dims are checked
634  
635 =head2 load_dcm_dir ( $dir,\%options)
636  
637 reads all dicom files in a dicrectory and returns a hash of hashes of piddles
638 based on the sort option and dcm_key.
639  
640  
641 =head2 parse_dcms ($hashref,\$options)
642  
643 Parses and sorts a hash of hashes of dicoms (such as returned by load_dcm_dir)
644 based on dcm_key and dim_idx. Returns a hash of piddles.
645  
646 =head2 unpack_field
647  
648 unpacks dicom fields and walks subfield structures recursively.
649  
650 =head2 sort_series
651  
652 Groups dicom files based on their series number. If data within the series
653 don't fit, the outcome depends on the split option. If set, it will always
654 produce several piddles, appending a, b, c, etc.; if not, transposition is tried,
655 ignoring Pixel Spacing and Image Rotation. Only if this fails, data is split.
656  
657 =head2 read_dcm ($file, \%options)
658  
659 reads a dicom file and creates a piddle-with-header structure.
660  
661 =head2 printStruct
662  
663 This is used to generate human readable and parsable text from the headers.
664  
665 =head1 TODO
666  
667 write tests!
668  
669 Since all data in a directory are loaded into memeory before sorting, this may
670 cause memory issues. At the moment, you only option is to split the files into
671 several directories, if you face problems.
672  
673 Generalise to other modalities. This will be done based on data available,
674 request or as needed.
675  
676 =cut
677  
678  
679 =head1 LICENSE AND COPYRIGHT
680  
681 Copyright 2016 Albrecht Ingo Schmid.
682  
683 This program is free software; you can redistribute it and/or modify it
684 under the terms of the the Artistic License (2.0). You may obtain a
685 copy of the full license at:
686  
687 L<http://www.perlfoundation.org/artistic_license_2_0>
688  
689 Any use, modification, and distribution of the Standard or Modified
690 Versions is governed by this Artistic License. By using, modifying or
691 distributing the Package, you accept this license. Do not use, modify,
692 or distribute the Package, if you do not accept this license.
693  
694 If your Modified Version has been derived from a Modified Version made
695 by someone other than you, you are nevertheless required to ensure that
696 your Modified Version complies with the requirements of this license.
697  
698 This license does not grant you the right to use any trademark, service
699 mark, tradename, or logo of the Copyright Holder.
700  
701 This license includes the non-exclusive, worldwide, free-of-charge
702 patent license to make, have made, use, offer to sell, sell, import and
703 otherwise transfer the Package with respect to any patent claims
704 licensable by the Copyright Holder that are necessarily infringed by the
705 Package. If you institute patent litigation (including a cross-claim or
706 counterclaim) against any party alleging that the Package constitutes
707 direct or contributory patent infringement, then this Artistic License
708 to you shall terminate on the date that such litigation is filed.
709  
710 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
711 AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
712 THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
713 PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
714 YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
715 CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
716 CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
717 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
718  
719  
720 =cut
721  
722 __END__
« lib/PDL/IO/Dcm/Plugins/MRISiemens.pm ↑ Summary lib/PDL/IO/Dcm/Plugins/Primitive.pm »