title: Detecting a line in a JPEG image
body: <p>I'm new to Swift and image processing but I didn't find any program to do what I wanted. I have thousands of pages of questionnaires but the OMR freeware (Optical Mark Recognition) I use fails to detect the boxes. That is because the questionnaires were printed by me or by the participants in the study yielding to different images (scale and rotation). Redressing the image is not sufficient. Lucky me, there is an horizontal line somewhere on top of each pages. So, the algorithm would look something like this:</p>
  
  <ol>
  <li>Select all the JPEG to transform (done)</li>
  <li>Enter the coordinates of the target line (done)</li>
  <li>For each JPEG image
  3a. Load the image (NSData? not UIImage since it is an App)
  3b. Uncompress the image
  3c. Detect the line on top of the page
  3d. Calculate and apply the angle and the translation (I found a free source in Java doing that)
  3e. Save the image under a modified name</li>
  </ol>
  
  <p>I need your help for steps 3a-3b. For step 3c, shall I use Canny edge detector followed by Hough transform?</p>
  
  <p>Any thoughts would be appreciated.</p>
  
  <p>---- EDIT ----</p>
  
  <p>Here is an image describing the problem. On the upper part (Patient #1), the coordinate of the top horizontal line are (294, 242) to (1437, 241). One the lower part (Patient #2), the coordinate of the top horizontal line are (299, 230) to (1439, 230). This seems a small difference but the OMR looks at the ROIs (i.e. boxes) with fixed coordinates. In other scanned images, the difference may be even greater and the top line may be not horizontal (e.g. (X1, Y1) = (320, 235) and (X2, Y2) = (1480, 220)).</p>
  
  <p>My idea is to get a template for the check boxes (the OMR does it) and coordinates of the top line once for ever (I can get them with Paint or whatever). Then align all the images to this template (using their top line) before running the OMR. There may be a scaling, a rotation and a translation needed. In other words, all the images should be perfectly stackable on the template image for the OMR to perform correctly...</p>
  
  <p><a href="https://i.stack.imgur.com/e6yRo.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e6yRo.jpg" alt="enter image description here"></a></p>
  
  <p>--- EDIT Dec 26th ---</p>
  
  <p>I've translated into Swift the Probabilistic Hough Transform of OpenCV (<a href="https://github.com/opencv/opencv/blob/d5323ce8482cd510f6d49c0e7336748c6aee4a61/modules/imgproc/src/hough.cpp#L415" rel="nofollow noreferrer">open cpp code from GitHub</a>. Unfortunately, the segments detected are too short (i.e. the entire line segment is not captured). I'm wondering: does it make sense to use Canny Edge Detector before Hough Transform to detect a single segment of a black line on a white page?</p>