{"id":21657478,"url":"https://github.com/aliakseis/detect-lines","last_synced_at":"2026-05-16T22:31:22.630Z","repository":{"id":93559423,"uuid":"278570107","full_name":"aliakseis/detect-lines","owner":"aliakseis","description":"exercise in classical computer vision","archived":false,"fork":false,"pushed_at":"2025-10-04T10:50:34.000Z","size":2474,"stargazers_count":2,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-10-04T12:28:02.766Z","etag":null,"topics":["ceres-solver","fourier-analysis","opencv"],"latest_commit_sha":null,"homepage":"","language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/aliakseis.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2020-07-10T07:37:00.000Z","updated_at":"2025-10-04T10:50:37.000Z","dependencies_parsed_at":"2023-03-13T17:17:34.015Z","dependency_job_id":null,"html_url":"https://github.com/aliakseis/detect-lines","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/aliakseis/detect-lines","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aliakseis%2Fdetect-lines","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aliakseis%2Fdetect-lines/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aliakseis%2Fdetect-lines/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aliakseis%2Fdetect-lines/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/aliakseis","download_url":"https://codeload.github.com/aliakseis/detect-lines/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aliakseis%2Fdetect-lines/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33121056,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-16T18:38:32.183Z","status":"ssl_error","status_checked_at":"2026-05-16T18:38:29.903Z","response_time":115,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ceres-solver","fourier-analysis","opencv"],"created_at":"2024-11-25T09:22:05.776Z","updated_at":"2026-05-16T22:31:22.624Z","avatar_url":"https://github.com/aliakseis.png","language":"C++","funding_links":[],"categories":[],"sub_categories":[],"readme":"# detect-lines\n\n![alt text](images/IMG_1427.JPG)\n\n## Overview\n\n**detect-lines** is a C++ project that implements advanced line detection and separation techniques for digital images.  \nIt combines classic computer vision (OpenCV), frequency-domain analysis (spectral methods), geometric filtering, and optimization techniques to robustly detect structural lines in images with noise, texture, or uneven illumination.\n\nThis project is particularly suited for tasks such as:\n- Detecting boundaries or separation lines in scanned documents, maps, or technical drawings\n- Identifying dominant structural features (edges, borders, stripes) in natural images\n- Preprocessing images for later pattern recognition or geometric analysis\n\n---\n\n* Image reading\n* Image low pass filtering\n* Emphasis on low image intensities:\n* Background subtraction, horizontal stripes removal\n\n* Obtaining one-dimensional (special case) Fourier spectra for image fragments using https://github.com/leerichardson/tree-swdft-2D\n* Finding the separation line points where spectra main frequencies abruptly change\n* Preliminary filtering of points using cv::partition and nanoflann library \n* Using RANSAC to find the separation line using separation line points\n* Using CERES solver to refine the separation line\n\n* Using both adaptiveThreshold and binary background subtraction to generate threshold image\n* Using thinning to obtain lines skeletons\n* Calling erode/dilate to filter out vertical lines\n* Invoking HoughLinesP to generate lines from skeletons\n* Merging lines according to https://stackoverflow.com/a/51121483/10472202\n* Filtering out short lines\n* Cutting lines using the RANSAC/CERES separation line mentioned above\n* Filtering out short lines once more\n\n* Search for the beginnings of short stripes with \"known good\" SURF data\n* Movement to the left and up along long lines\n\n* Merging HoughLinesP and SURF results to obtain the final data\n\n---\n\n## Technical Architecture\n\nThe project is structured as a modular C++/OpenCV pipeline:\n\n### 1. Input and Preprocessing\n- **`main.cpp`**  \n  Entry point. Reads image(s), invokes the detection pipeline, and writes results.  \n- **Preprocessing steps:**  \n  - Image loading (`cv::imread`)  \n  - Optional downscaling for speed  \n  - Low-pass filtering (Gaussian blur)  \n  - Intensity emphasis on darker features  \n  - Background subtraction and horizontal stripe removal  \n\n---\n\n### 2. Frequency-Domain Line Candidate Detection\n- **`tswdft2d.h` integration**  \n  Uses **tree-structured sliding-window DFT (SWDFT)** to compute localized spectra.  \n- Detects **frequency discontinuities**: sudden changes in spectral energy correspond to possible separation lines.  \n- Produces a set of candidate “line points” across image fragments.\n\n---\n\n### 3. Geometric Filtering\n- **`detect-lines.cpp/.h`**  \n  Core functionality:  \n  - Uses `cv::partition` to cluster nearby candidate points.  \n  - Uses `nanoflann.hpp` (KD-tree) for efficient nearest-neighbor queries and spatial filtering.  \n- Output: refined set of potential line-supporting points.\n\n---\n\n### 4. Model Fitting and Refinement\n- **RANSAC**  \n  Robustly fits a line to candidate points while ignoring outliers.  \n- **Ceres Solver**  \n  Refines the fitted model to minimize geometric error. Provides sub-pixel accuracy and robust handling of noisy data.  \n- **`known-good.cpp/.h`**  \n  Contains reference/validation code for verifying correct line detection.\n\n---\n\n### 5. Morphological and Skeleton Processing\n- Adaptive thresholding and background subtraction produce a binarized image.  \n- **Morphological thinning** generates a skeleton representation.  \n- **Erosion/Dilation** filters out vertical lines when needed.\n\n---\n\n### 6. Probabilistic Hough Transform\n- OpenCV’s `cv::HoughLinesP` is used to detect line segments from skeletonized images.  \n- Detected segments are filtered based on:\n  - Orientation  \n  - Length  \n  - Consistency with RANSAC/Ceres line model  \n\n---\n\n### 7. Output\n- Result images are stored under `results/`, including intermediate visualizations such as:\n  - Reduced candidate lines\n  - Skeletons\n  - Hough transform output\n  - Final refined separation line\n\n---\n\n## Code Components\n\n| File              | Purpose                                                                 |\n|-------------------|-------------------------------------------------------------------------|\n| `main.cpp`        | Orchestrates the pipeline, handles I/O and visualization.              |\n| `detect-lines.*`  | Core algorithms for candidate point detection and line filtering.       |\n| `convert.cpp`     | Image conversions and helper routines.                                 |\n| `known-good.*`    | Reference validation routines and test logic.                          |\n| `nanoflann.hpp`   | KD-tree library for fast nearest-neighbor queries.                     |\n| `tswdft2d.h`      | Tree-structured SWDFT for localized Fourier analysis.                  |\n| `CMakeLists.txt`  | Build system configuration (CMake).                                    |\n\n---\n\n## Algorithmic Highlights\n\n1. **Hybrid Spatial–Frequency Approach**  \n   - Spatial domain: filtering, thresholding, morphology.  \n   - Frequency domain: discontinuity detection using SWDFT.  \n\n2. **Multi-Stage Line Refinement**  \n   - Candidate extraction → clustering → RANSAC → Ceres optimization.  \n\n3. **Efficiency Considerations**  \n   - KD-tree search (`nanoflann`) for scalable point clustering.  \n   - Intermediate results stored for debugging and reproducibility.  \n\n---\n\n## Results\n\nExample outputs are stored under `results/`:\n\n![alt text](results/borderline0.jpg)\n![alt text](results/Detected_Lines_(in_red)_-_Probabilistic_Line_Transform.jpg)\n![alt text](results/Diff.jpg)\n![alt text](results/Dst_before.jpg)\n![alt text](results/func.jpg)\n![alt text](results/image.jpg)\n![alt text](results/imgCoherencyBin.jpg)\n![alt text](results/imgOrientationBin.jpg)\n![alt text](results/Mask.jpg)\n![alt text](results/outSkeleton.jpg)\n![alt text](results/qrwer.jpg)\n![alt text](results/Reduced_Lines.jpg)\n![alt text](results/Reduced_Lines_0.jpg)\n![alt text](results/theMask.jpg)\n![alt text](results/Thinning.jpg)\n![alt text](results/Transform.jpg)\n\nThese demonstrate the progressive filtering and refinement pipeline.\n\n---\n\n## Technical Architecture\n\n### 1. Thinning Algorithm\n\nThe code provides implementations of **Zhang–Suen** and **Guo–Hall** thinning methods to reduce binary images to skeletons:\n\n```cpp\nenum ThinningTypes {\n    THINNING_ZHANGSUEN = 0,  // Zhang-Suen thinning\n    THINNING_GUOHALL   = 1   // Guo-Hall thinning\n};\n\n// Applies one thinning iteration\nvoid thinningIteration(cv::Mat\u0026 img, int iter, ThinningTypes type);\n\n```\n\nSkeletonization makes subsequent Hough line detection more robust.\n\n### 2. Candidate Line Detection (Spectral + Spatial)\nSpectral analysis finds abrupt changes in local Fourier spectra:\n\n```cpp\n// Sliding Window DFT for 2D fragments\n#include \"tswdft2d.h\"\n\n// Detect separation line points where spectra change\nstd::vector\u003ccv::Point\u003e detectFrequencyDiscontinuities(const cv::Mat\u0026 fragment);\n```\nPoints are then clustered using OpenCV and nanoflann:\n\n```cpp\n// KD-tree neighbor search\nnanoflann::KDTreeSingleIndexAdaptor\u003c\n    nanoflann::L2_Simple_Adaptor\u003cdouble, PointCloud\u003e,\n    PointCloud, 2\u003e index(2, cloud, KDTreeParams(10));\n```\n### 3. RANSAC Model Fitting\nRobust line fitting rejects outliers:\n\n```cpp\ncv::Vec4f fittedLine;\ncv::fitLine(candidatePoints, fittedLine,\n            cv::DIST_L2, 0, 0.01, 0.01);\n```\n### 4. Optimization with Ceres Solver\nAfter RANSAC, line parameters are refined by nonlinear least squares using Ceres:\n\n```cpp\nstruct LineResidual {\n    LineResidual(double x, double y) : _x(x), _y(y) {}\n    template \u003ctypename T\u003e\n    bool operator()(const T* const line, T* residual) const {\n        residual[0] = line[0] * T(_x) + line[1] * T(_y) + line[2];\n        return true;\n    }\n    double _x, _y;\n};\n```\nThis improves sub-pixel precision of the detected separation line.\n\n### 5. Morphology + Hough Transform\nThe pipeline combines adaptive thresholding, skeletonization, and Hough Transform:\n\n```cpp\ncv::Mat edges;\ncv::adaptiveThreshold(gray, edges, 255,\n                      cv::ADAPTIVE_THRESH_MEAN_C,\n                      cv::THRESH_BINARY, 15, -2);\n\n// Probabilistic Hough Transform\nstd::vector\u003ccv::Vec4i\u003e lines;\ncv::HoughLinesP(edges, lines, 1, CV_PI/180, 80, 30, 10);\n```\nLines are then filtered based on orientation, length, and consistency.\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faliakseis%2Fdetect-lines","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faliakseis%2Fdetect-lines","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faliakseis%2Fdetect-lines/lists"}