Search code examples
pythonopencvhough-transform

Distance between cv2 lienes and centre of screen - python


I'm using openCV to detect the distance between two lines and their position relative to the centre point of an image. Doesn't need to be an exact distance - just a contextual value of some sort (pixels would be fine)

My code which I have working detecting the two lines is this;

import PIL
import time
import io
import picamera
import cv2
import numpy as np

image_count = 0

with picamera.PiCamera() as camera:
    camera.start_preview()
    camera.resolution = (340, 240)
    time.sleep(2)

while(True):
    try:
        stream = io.BytesIO()
        image_counter+=1
        camera.capture(stream, format='png')
        data = np.fromstring(stream.getvalue(), dtype=np.uint8)
        image = cv2.imdecode(data, 1)
        grey_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        edge_image = cv2.Canny(grey_image, 50, 150, apertureSize = 3)
        lines = cv2.HoughLines(edge_image, 1, np.pi/180, 95)
        if(lines.any):
            for rho, theta in lines[0]
                a = np.cos(theta)
                b = np.sin(theta)
                x0 = a*rho
                y0 = b*rho
                x1 = int(x0 + 1000*(-b))
                y1 = int(y0 + 1000*(a))
                x2 = int(x0 - 1000*(-b))
                y2 = int(y0 - 1000*(a))

                cv2.line(image, (x1, y1), (x2, y2), (0,0,255), 2)

            cv2.imwrite('lined_image_' + str(image_counter) + '.png, image)

    except:
        print 'loop error'

It detects lines such as in this image;

lines around boundaries

I've been trying to work out how to do this numerically but it's convoluted and probably wrong - there must be an easier way but I can't see it with my inexperience using open CV.

How can I find the distance between the centre point of the image and the innermost red lines you see? (at the point where the lines intersects the horizontal line which intersects both in and the images centre point)

Thanks!


Solution

  • If you were to use HoughLinesP, you'd directly get start and end points of the lines. Then, when Dx is (x2-x1) and Dy is (y2-y1), your required distance d from the centre point (x0,y0) is

    enter image description here

    If you intend to stick with HoughLines, you can easily transform rho and theta to get the equation of a line, and use one of the many formulae described here, which is also where the above formula has been borrowed from.