title: How to detect parallel lines in a similar path using OpenCV in Python?
body: <p>I am given a task to detect all rectangular objects in the image. It's very simple if I use <strong>cv2.findContours</strong> function in OpenCV. However, I am not allowed to use it. I am told to detect all <strong>parallel lines</strong> and then highlight them. I am using Hough Transform to find all lines and then find parallel lines according to their slope. But somehow the number of lines is very large and the result is not accurate at all.</p>
  
  <p>Below is my code, anyone knows how to fix it?</p>
  
  <pre><code>import cv2
  import numpy as np
  
  
  def getSlopeOfLine(line):
      xDis = line[0][2] - line[0][0]
      if (xDis == 0):
          return None
      return (line[0][3] - line[0][1]) / xDis
  
  
  if __name__ == '__main__':
      inputFileName = '/Users/James/Desktop/img.jpg'
      img = cv2.imread(inputFileName)
  
      gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  
      lines = cv2.HoughLinesP(gray, 1, np.pi / 180, 100, 30, 2)
  
      parallelLines = []
      for a in lines:
          for b in lines:
              if a is not b:
                  slopeA = getSlopeOfLine(b)
                  slopeB = getSlopeOfLine(b)
                  if slopeA is not None and slopeB is not None:
                      if 0 &lt;= abs(slopeA - slopeB) &lt;= 0.6:
                          parallelLines.append({'lineA': a, 'lineB': b})
  
      for pairs in parallelLines:
          lineA = pairs['lineA']
          lineB = pairs['lineB']
  
          leftx, boty, rightx, topy = lineA[0]
          cv2.line(img, (leftx, boty), (rightx, topy), (0, 0, 255), 2)
  
      cv2.imshow('linesImg', img)
      cv2.waitKey(0)
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/2xCkW.jpg" rel="nofollow noreferrer">source image</a></p>