ITK  6.0.0
Insight Toolkit
SphinxExamples/src/Numerics/Statistics/HistogramCreationAndBinAccess/Code.py
1 #!/usr/bin/env python
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 from __future__ import print_function
18 
19 import itk
20 
21 numberOfComponents = 2
22 
23 histogram = itk.Histogram.New(MeasurementVectorSize=numberOfComponents)
24 
25 # We initialize it as a 3x3 histogram with equal size intervals.
26 size = itk.Array.UL(numberOfComponents)
27 size.Fill(3)
28 
29 lowerBound = 1.1, 2.6
30 upperBound = 7.1, 8.6
31 histogram.Initialize(size, lowerBound, upperBound)
32 
33 # Now the histogram is ready for storing frequency values. There
34 # are three ways of accessing data elements in the histogram:
35 # - using instance identifiers---just like any other Sample object;
36 # - using n-dimensional indices---just like an Image object;
37 # - using an iterator---just like any other Sample object.
38 #
39 # In this example, the index (0, 0) refers the same bin as the instance
40 # identifier (0) refers to. The instance identifier of the index (0,
41 # 1) is (3), (0, 2) is (6), (2, 2) is (8), and so on.
42 
43 frequencies = [(0, 0), (1, 2), (2, 3), (3, 2), (4, 1), (5, 1), (6, 5), (7, 4), (8, 0)]
44 
45 for instance_identifier, frequency in frequencies:
46  histogram.SetFrequency(instance_identifier, frequency)
47 
48 # Let us examine if the frequency is set correctly by calling the
49 # GetFrequency(index) method. We can use the
50 # GetFrequency(instance identifier) method for the same purpose.
51 
52 index = [0, 2]
53 print(
54  "Frequency of the bin at index",
55  index,
56  "is",
57  histogram.GetFrequency(index),
58  "and the bin's instance identifier is",
59  histogram.GetInstanceIdentifier(index),
60 )