ITK 6.0.0
Insight Toolkit
 
Loading...
Searching...
No Matches
itkInd2Sub.h
Go to the documentation of this file.
1/*=========================================================================
2 *
3 * Copyright NumFOCUS
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * https://www.apache.org/licenses/LICENSE-2.0.txt
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 *=========================================================================*/
18
19#ifndef itkInd2Sub_h
20#define itkInd2Sub_h
21#include <itkFixedArray.h>
22#include <iostream>
23#include <itkIndex.h>
24#include <itkSize.h>
25
26namespace itk
27{
40template <unsigned int VN>
42Ind2Sub(const unsigned int & linear_index, const FixedArray<unsigned int, VN> & ns)
43{
44 for (unsigned int d = 0; d < VN; ++d)
45 {
46 if (ns[d] == 0)
47 throw std::runtime_error("itk::Ind2Sub: input size cannot be zero");
48 }
49
50 // accumulative product.
52 unsigned int accum = 1;
53 cumprod[0] = accum;
54 for (unsigned int d = 1; d < VN; ++d)
55 {
56 accum *= ns[d - 1];
57 cumprod[d] = accum;
58 }
59 unsigned int max_index = accum * ns[VN - 1] - 1;
60 if (linear_index > max_index)
61 throw std::runtime_error("itk::Ind2Sub: input index is incompatible with the given size");
62
64 unsigned int temp_index(linear_index);
65 // loop well defined. it will go to > N after --0
66 for (unsigned int i = VN - 1; i < VN; --i)
67 {
68 unsigned int rem = (temp_index) % cumprod[i];
69 out[i] = (temp_index - rem) / cumprod[i];
70 temp_index = rem;
71 }
72
73 return out;
74}
75
80template <unsigned int VN>
82Ind2Sub(const unsigned int & linear_index, const itk::Size<VN> & ns)
83{
85 for (unsigned int d = 0; d < VN; ++d)
86 {
87 ns_array[d] = ns[d];
88 }
89 FixedArray<unsigned int, VN> out_array = Ind2Sub<VN>(linear_index, ns_array);
90 itk::Index<VN> out_index;
91 for (unsigned int d = 0; d < VN; ++d)
92 {
93 out_index[d] = out_array[d];
94 }
95
96 return out_index;
97}
98} // end namespace itk
99#endif
Simulate a standard C array with copy semantics.
The "itk" namespace contains all Insight Segmentation and Registration Toolkit (ITK) classes....
FixedArray< unsigned int, VN > Ind2Sub(const unsigned int &linear_index, const FixedArray< unsigned int, VN > &ns)
Return SubIndex [i,j,k,...] from linear index and matrix size. Based on Ind2Sub from Matlab.
Definition itkInd2Sub.h:42
Represent a n-dimensional index in a n-dimensional image.
Definition itkIndex.h:69
Represent a n-dimensional size (bounds) of a n-dimensional image.
Definition itkSize.h:70