2

Consider three points A, B, C in an image.

enter image description here

Below are their coordinates in the image of size 300x300.

enter image description here

I am trying to detect and draw a line connecting through these three points using below HoughLinesP code.

import cv2
import numpy as np

img = cv2.imread('test.png')
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #Convert img to grayscale 
lines = cv2.HoughLinesP(img, rho=1, theta=np.pi/180, threshold=1, minLineLength=5, maxLineGap=10)
print(lines)

for line in lines:
    x1, y1, x2, y2 = line[0]
    cv2.line(img, (x1, y1), (x2, y2), 255, 1)
cv2.imshow("result", img)

But it detects a line that passes through only B and C. Why is it so?

Output:
[[[110 100 120 100]]]

enter image description here

GreenHeart
  • 73
  • 1
  • 6

2 Answers2

2

cv2.HoughLinesP() is mainly used for detecting a line, not really used for drawing. To draw a line given your three points, there are a few other options you can try. The first method is to filter the points by finding the leftmost and rightmost points then drawing the line with cv2.line(). Another approach is to find all the points then use cv2.fillPoly(). A third method is to use cv2.polylines()

enter image description here

import cv2
import numpy as np

image = cv2.imread('1.png')
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
coords = np.column_stack(np.where(gray > 0))
coords = np.rot90(coords, 2)
cv2.fillPoly(image, [coords], (36,255,12)) # or
# cv2.polylines(image, [coords], 1, (36,255,12))

cv2.imshow('image', image)
cv2.imwrite('image.png', image)
cv2.waitKey()
nathancy
  • 42,661
  • 14
  • 115
  • 137
  • HoughLinesP is mainly used for detecting lines, in your image you have three points instead of a line. Maybe after filling the points to create a line then you can use HoughLinesP – nathancy Sep 17 '19 at 20:28
  • Thank you. This dots and image is for just to understand the working of HoughLinesP with threshold parameter. And I believe it works by joining points (not only lines) that appears in straight line. – GreenHeart Sep 17 '19 at 20:44
  • HoughLinesP worked after increasing the Accumulator's resolution and threshold. – GreenHeart Sep 19 '19 at 13:58
0
  • Increase the Accumulator's Resolution by giving much smaller values for rho and theta.
  • Set Accumulator's threshold to minimum 2.
lines = cv2.HoughLinesP(img, rho=0.1, theta=np.pi/180 * 0.1, threshold=2, minLineLength=5, maxLineGap=10)

enter image description here

GreenHeart
  • 73
  • 1
  • 6