1

Say I have an image like this:

enter image description here

I want the location of the start and end points of the black strip in the image matrix.

I have tried several method like horizontal line detection in Python OpenCV and have come up with following code that gets me the lines highlighted:

import cv2
import numpy as np
from numpy import array
from matplotlib import pyplot as plt
import math

img = cv2.imread('caption.jpg')

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150, apertureSize = 3)
lines = cv2.HoughLinesP(edges, 1,np.pi/180,350);
for line in lines[0]:
    pt1 = (line[0],line[1])
    pt2 = (line[2],line[3])
    cv2.line(img, pt1, pt2, (0,0,255))



gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150,apertureSize = 3)

print img.shape

lines = cv2.HoughLines(edges,1,np.pi/180,350)

for rho,theta in lines[0]:
    a = np.cos(theta)
    b = np.sin(theta)
    if int(b) == 1: #only horizontal lines with cos theta(theta = 0) = 1
        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(img,(x1,y1),(x2,y2),(0,0,255),2)

cv2.imshow('edges', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Result: enter image description here

If I try print x1, y1, x2, y2 i get

-1000 781 999 782 -1000 712 999 713

So these obviously are not the location points in the image matrix like x is negative.

What is the location of the start and endpoints of these lines in the image matrix? I need to perform some point operation on the pixels in that area and hence need the start and endpoints.

Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
gabbar0x
  • 4,046
  • 5
  • 31
  • 51

1 Answers1

1

These lines will always return -1000 + the original point

x1 = int(x0 + 1000*(-b))
x2 = int(x0 - 1000*(-b))

As you only get into this loop if int(b) == 1:

Which means that you need to print the x0 directly, since the above lines will always be (x0 + (-1000)), in this case x0 is 0 since it starts from the left of the image.

MoustafaS
  • 1,991
  • 11
  • 20
  • What about y? I mean I have x0 and y0 for the first line what about the second? What are the starting points of the second line? – gabbar0x Sep 05 '16 at 05:50
  • Also, how do I access this in the matrix? It is surely not at img[x0] since x0 is 0 and it is the first row – gabbar0x Sep 05 '16 at 06:03