-
Notifications
You must be signed in to change notification settings - Fork 2
/
HoughTransform.cs
118 lines (108 loc) · 3.77 KB
/
HoughTransform.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MathNet.Numerics.LinearAlgebra.Single;
namespace VisionNET
{
/// <summary>
/// Class encapsulating the logic for a Hough transform.
/// </summary>
public class HoughTransform
{
private class Index
{
private int[] _values;
public Index(params int[] values)
{
_values = values;
}
public List<Index> Neighbors()
{
List<Index> neighbors = new List<Index>();
for (int i = 0; i < _values.Length; i++)
{
int[] copy = (int[])_values.Clone();
copy[i] = _values[i] - 1;
neighbors.Add(new Index(copy));
copy = (int[])_values.Clone();
copy[i] = _values[i] + 1;
neighbors.Add(new Index(copy));
}
return neighbors;
}
public override bool Equals(object obj)
{
if (obj is Index)
{
int[] compare = (obj as Index)._values;
if (compare.Length == _values.Length)
{
for (int i = 0; i < compare.Length; i++)
if (compare[i] != _values[i])
return false;
return true;
}
else return false;
}
else return false;
}
public override int GetHashCode()
{
int sum = 0;
foreach (int val in _values)
sum = 7 * sum + 13 * val;
return sum;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("({0}", _values[0]);
for (int i = 1; i < _values.Length; i++)
sb.AppendFormat(", {0}", _values[i]);
sb.Append(")");
return sb.ToString();
}
public Vector ToVector(int binSize)
{
return new DenseVector(_values.Select(o => (float)o * binSize).ToArray());
}
}
private int _binSize;
private Dictionary<Index, List<Vector>> _transform;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="binSize">The size of the bins</param>
/// <param name="data">Data to transform</param>
public HoughTransform(int binSize, List<Vector> data)
{
_binSize = binSize;
_transform = new Dictionary<Index, List<Vector>>();
foreach (Vector point in data)
{
Index index = new Index(point.Select(o => (int)(o / binSize)).ToArray());
if (!_transform.ContainsKey(index))
_transform[index] = new List<Vector>();
_transform[index].Add(point);
foreach(Index neighbor in index.Neighbors())
{
if (!_transform.ContainsKey(neighbor))
_transform[neighbor] = new List<Vector>();
_transform[neighbor].Add(point);
}
}
}
/// <summary>
/// Returns the bins and their contents.
/// </summary>
/// <returns>The transform bins</returns>
public List<KeyValuePair<Vector, List<Vector>>> Bins
{
get
{
return _transform.Select(o => new KeyValuePair<Vector, List<Vector>>(o.Key.ToVector(_binSize), o.Value)).ToList();
}
}
}
}