1use lib_jsl_core::ErrorsJSL;
16use ndarray::Array2;
17use std::f64::consts::PI;
18
19#[derive(Clone, Debug, PartialEq)]
21pub struct HoughLines {
22 pub accumulator: Array2<u32>,
24 pub thetas: Vec<f64>,
26 pub rho_min: f64,
28 pub rho_step: f64,
30}
31
32impl HoughLines {
33 pub fn rho(&self, i: usize) -> f64 {
35 self.rho_min + i as f64 * self.rho_step
36 }
37}
38
39#[derive(Clone, Copy, Debug, PartialEq)]
41pub struct HoughLine {
42 pub rho: f64,
43 pub theta: f64,
44 pub votes: u32,
45}
46
47pub fn hough_transform(edges: &Array2<bool>, num_angles: usize, rho_resolution: f64) -> Result<HoughLines, ErrorsJSL> {
50 if num_angles < 2 || !(rho_resolution > 0.0) {
51 return Err(ErrorsJSL::InvalidInputRange("Need at least 2 angles and a positive rho resolution"));
52 }
53 let (rows, cols) = edges.dim();
54 if rows == 0 || cols == 0 {
55 return Err(ErrorsJSL::InvalidInputRange("Edge map must be non-empty"));
56 }
57 let diag = ((rows * rows + cols * cols) as f64).sqrt();
58 let n_rho = (2.0 * diag / rho_resolution).ceil() as usize + 1;
59 let rho_min = -diag;
60 let thetas: Vec<f64> = (0..num_angles).map(|j| j as f64 * PI / num_angles as f64).collect();
61 let trig: Vec<(f64, f64)> = thetas.iter().map(|t| (t.cos(), t.sin())).collect();
62 let mut acc = Array2::<u32>::zeros((n_rho, num_angles));
63 for ((r, c), &e) in edges.indexed_iter() {
65 if !e {
66 continue;
67 }
68 let (x, y) = (c as f64, r as f64);
69 for (j, (cos, sin)) in trig.iter().enumerate() {
70 let bin = ((x * cos + y * sin - rho_min) / rho_resolution).round() as usize;
71 acc[(bin, j)] += 1;
72 }
73 }
74 Ok(HoughLines { accumulator: acc, thetas, rho_min, rho_step: rho_resolution })
76}
77
78pub fn hough_line_peaks(h: &HoughLines, min_votes: u32, max_lines: usize, min_rho_bins: usize, min_theta_bins: usize) -> Vec<HoughLine> {
82 let (n_rho, n_theta) = h.accumulator.dim();
83 let mut cells: Vec<(u32, usize, usize)> = h.accumulator.indexed_iter().filter(|(_, v)| **v >= min_votes && **v > 0).map(|((i, j), &v)| (v, i, j)).collect();
84 cells.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)).then(a.2.cmp(&b.2)));
85 let mut suppressed = Array2::from_elem((n_rho, n_theta), false);
86 let mut out = Vec::new();
87 for (votes, i, j) in cells {
88 if out.len() >= max_lines {
89 break;
90 }
91 if suppressed[(i, j)] {
92 continue;
93 }
94 out.push(HoughLine { rho: h.rho(i), theta: h.thetas[j], votes });
95 for dj in -(min_theta_bins as isize)..=min_theta_bins as isize {
96 let jj = j as isize + dj;
97 let (jw, flip) = if jj < 0 { ((jj + n_theta as isize) as usize, true) } else if jj >= n_theta as isize { ((jj - n_theta as isize) as usize, true) } else { (jj as usize, false) };
99 for di in -(min_rho_bins as isize)..=min_rho_bins as isize {
100 let ii = i as isize + di;
101 let ii = if flip { n_rho as isize - 1 - ii } else { ii };
102 if (0..n_rho as isize).contains(&ii) {
103 suppressed[(ii as usize, jw)] = true;
104 }
105 }
106 }
107 }
108 out
109}
110
111#[derive(Clone, Copy, Debug, PartialEq)]
113pub struct HoughCircle {
114 pub row: usize,
115 pub col: usize,
116 pub radius: usize,
117 pub votes: u32,
119 pub support: f64,
123}
124
125pub fn hough_circles(edges: &Array2<bool>, radii: &[usize], min_support: f64, min_distance: usize) -> Result<Vec<HoughCircle>, ErrorsJSL> {
129 let (rows, cols) = edges.dim();
130 if rows == 0 || cols == 0 || radii.is_empty() || radii.contains(&0) {
131 return Err(ErrorsJSL::InvalidInputRange("Need a non-empty edge map and positive radii"));
132 }
133 if !(min_support > 0.0) {
134 return Err(ErrorsJSL::InvalidInputRange("min_support must be positive"));
135 }
136 let mut found: Vec<HoughCircle> = Vec::new();
137 for &radius in radii {
138 let circumference = 2.0 * PI * radius as f64;
139 let steps = (circumference.ceil() as usize * 2).max(16);
140 let offsets: Vec<(isize, isize)> = {
141 let mut o: Vec<(isize, isize)> = (0..steps)
142 .map(|k| {
143 let a = 2.0 * PI * k as f64 / steps as f64;
144 ((radius as f64 * a.sin()).round() as isize, (radius as f64 * a.cos()).round() as isize)
145 })
146 .collect();
147 o.sort_unstable();
148 o.dedup(); o
150 };
151 let mut acc = Array2::<u32>::zeros((rows, cols));
152 for ((r, c), &e) in edges.indexed_iter() {
153 if !e {
154 continue;
155 }
156 for &(dr, dc) in &offsets {
157 let (cr, cc) = (r as isize + dr, c as isize + dc);
158 if cr >= 0 && cc >= 0 && cr < rows as isize && cc < cols as isize {
159 acc[(cr as usize, cc as usize)] += 1;
160 }
161 }
162 }
163 let need = (min_support * circumference).ceil() as u32;
164 for ((r, c), &v) in acc.indexed_iter() {
165 if v >= need.max(1) {
166 found.push(HoughCircle { row: r, col: c, radius, votes: v, support: v as f64 / circumference });
167 }
168 }
169 }
170 found.sort_by(|a, b| b.votes.cmp(&a.votes).then(a.row.cmp(&b.row)).then(a.col.cmp(&b.col)));
171 let mut kept: Vec<HoughCircle> = Vec::new();
172 for c in found {
173 if kept.iter().all(|k| ((k.row as f64 - c.row as f64).powi(2) + (k.col as f64 - c.col as f64).powi(2)).sqrt() >= min_distance as f64) {
174 kept.push(c);
175 }
176 }
177 Ok(kept)
178}
179
180pub fn hough_lines(edges: &Array2<bool>, min_votes: u32, max_lines: usize) -> Result<Vec<HoughLine>, ErrorsJSL> {
183 let h = hough_transform(edges, 180, 1.0)?;
184 Ok(hough_line_peaks(&h, min_votes, max_lines, 4, 8))
185}
186
187#[cfg(test)]
188mod tests {
189 use super::*;
190
191 fn draw_line(a: &mut Array2<bool>, from: (usize, usize), to: (usize, usize)) {
192 let n = ((to.0 as f64 - from.0 as f64).abs().max((to.1 as f64 - from.1 as f64).abs())) as usize;
193 for k in 0..=n {
194 let t = k as f64 / n as f64;
195 let r = from.0 as f64 + t * (to.0 as f64 - from.0 as f64);
196 let c = from.1 as f64 + t * (to.1 as f64 - from.1 as f64);
197 a[(r.round() as usize, c.round() as usize)] = true;
198 }
199 }
200
201 fn draw_circle(a: &mut Array2<bool>, centre: (f64, f64), radius: f64) {
202 for k in 0..720 {
203 let t = k as f64 * PI / 360.0;
204 let (r, c) = ((centre.0 + radius * t.sin()).round(), (centre.1 + radius * t.cos()).round());
205 if r >= 0.0 && c >= 0.0 && (r as usize) < a.nrows() && (c as usize) < a.ncols() {
206 a[(r as usize, c as usize)] = true;
207 }
208 }
209 }
210
211 #[test]
212 fn axis_aligned_lines_have_the_expected_parameters_and_vote_counts() {
213 let mut e = Array2::from_elem((100, 100), false);
214 draw_line(&mut e, (40, 0), (40, 99)); let lines = hough_lines(&e, 50, 5).unwrap();
216 assert_eq!(lines.len(), 1, "{lines:?}");
217 assert!((lines[0].theta - PI / 2.0).abs() < 1e-9 && (lines[0].rho - 40.0).abs() < 1.0, "{:?}", lines[0]);
218 assert_eq!(lines[0].votes, 100, "every pixel of the line voted for the same cell");
219
220 let mut v = Array2::from_elem((100, 100), false);
221 draw_line(&mut v, (0, 30), (99, 30)); let lines = hough_lines(&v, 50, 5).unwrap();
223 assert_eq!(lines.len(), 1);
224 assert!(lines[0].theta.abs() < 1e-9 && (lines[0].rho - 30.0).abs() < 1.0, "{:?}", lines[0]);
225 }
226
227 #[test]
228 fn a_diagonal_and_two_crossing_lines_are_all_found() {
229 let mut e = Array2::from_elem((100, 100), false);
230 draw_line(&mut e, (0, 0), (99, 99)); let lines = hough_lines(&e, 60, 3).unwrap();
232 assert_eq!(lines.len(), 1);
233 assert!((lines[0].theta - 135f64.to_radians()).abs() < 1e-9 && lines[0].rho.abs() < 1.0, "{:?}", lines[0]);
234 draw_line(&mut e, (20, 90), (80, 10));
235 draw_line(&mut e, (60, 0), (60, 99));
236 let lines = hough_lines(&e, 30, 10).unwrap();
239 assert_eq!(lines.len(), 3, "{lines:?}");
240 assert!(lines.windows(2).all(|w| w[0].votes >= w[1].votes), "strongest first");
241 let off_grid = lines.iter().min_by_key(|l| l.votes).unwrap();
242 assert!((off_grid.theta.to_degrees() - 53.13).abs() < 1.6 && off_grid.votes < 81, "{off_grid:?}");
243 }
244
245 #[test]
246 fn broken_lines_and_clutter_do_not_prevent_detection() {
247 let mut e = Array2::from_elem((120, 120), false);
248 draw_line(&mut e, (50, 0), (50, 119));
249 for c in 40..60 {
250 e[(50, c)] = false; }
252 let mut seed = 5u64;
253 for _ in 0..150 {
254 seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
255 let (r, c) = ((seed >> 33) as usize % 120, (seed >> 13) as usize % 120);
256 e[(r, c)] = true;
257 }
258 let lines = hough_lines(&e, 80, 3).unwrap();
259 assert!(!lines.is_empty() && (lines[0].theta - PI / 2.0).abs() < 1e-9 && (lines[0].rho - 50.0).abs() < 1.5, "{lines:?}");
260 assert!(lines[0].votes >= 100);
261 }
262
263 #[test]
264 fn suppression_wraps_across_theta_zero_without_duplicating_a_vertical_line() {
265 let mut e = Array2::from_elem((80, 80), false);
267 draw_line(&mut e, (0, 25), (79, 25));
268 let h = hough_transform(&e, 180, 1.0).unwrap();
269 let lines = hough_line_peaks(&h, 20, 10, 3, 6);
270 assert_eq!(lines.len(), 1, "{lines:?}");
271 }
272
273 #[test]
274 fn circles_are_located_and_their_radius_is_chosen_from_the_candidates() {
275 let mut e = Array2::from_elem((120, 120), false);
276 draw_circle(&mut e, (50.0, 60.0), 15.0);
277 let found = hough_circles(&e, &[10, 15, 20], 0.7, 8).unwrap();
278 assert!(!found.is_empty());
279 let best = found[0];
280 assert_eq!(best.radius, 15);
281 assert!((best.row as i32 - 50).abs() <= 1 && (best.col as i32 - 60).abs() <= 1, "{best:?}");
282 assert!(best.support > 0.9);
283 assert_eq!(found.iter().filter(|c| c.radius == 15).count(), 1);
285
286 draw_circle(&mut e, (90.0, 25.0), 12.0);
287 let both = hough_circles(&e, &[12, 15], 0.7, 10).unwrap();
288 assert!(both.iter().any(|c| c.radius == 15 && c.row.abs_diff(50) <= 1 && c.col.abs_diff(60) <= 1));
289 assert!(both.iter().any(|c| c.radius == 12 && c.row.abs_diff(90) <= 1 && c.col.abs_diff(25) <= 1));
290 }
291
292 #[test]
293 fn an_empty_edge_map_finds_nothing() {
294 let e = Array2::from_elem((30, 30), false);
295 assert!(hough_lines(&e, 1, 5).unwrap().is_empty());
296 assert!(hough_circles(&e, &[5], 0.5, 3).unwrap().is_empty());
297 }
298
299 #[test]
300 fn invalid_arguments() {
301 let e = Array2::from_elem((10, 10), false);
302 assert!(hough_transform(&e, 1, 1.0).is_err() && hough_transform(&e, 90, 0.0).is_err());
303 assert!(hough_transform(&Array2::from_elem((0, 5), false), 90, 1.0).is_err());
304 assert!(hough_circles(&e, &[], 0.5, 3).is_err() && hough_circles(&e, &[0], 0.5, 3).is_err() && hough_circles(&e, &[3], 0.0, 3).is_err());
305 }
306}