Search code examples
pythonnumpyopencvcomputer-visionhough-transform

OpenCV HoughLines Produces Too Many Lines Python


I have been working on using python and computer vision to detect the board state of a gameboard in a game called Go. Based on the data collected here, I planned to base my implementation off of this paper's algorithm(s). However, I ran into trouble when I got to section 3.1.2 in the paper and had to compute a Hough Transform on my image. I tried using OpenCV's Hough Line function, but got an image so full of lines I couldn't see the original image.

I tried various line thicknesses, and different thresholds values for previous functions but I always seemed to end up with either way too many lines or practically no lines at all. For example, when using the top image, I got the image below it with the code I pasted at the very bottom enter image description here

Hough Image

I assume that the though HoughLines function just produces so many lines that it covers the screen, but I can't seem to get a normal amount of lines. I'm not sure if this bit will be useful but I have to go to extremely high values of threshold compared to any tutorial or example I can find online to avoid an almost completely red screen, but even then only like 5 lines show up. I could just not use the HoughLines function but the next step of the paper depends on this result and so I either have to solve this or find a completely different implementation of this. Any help is appreciated on this. Thanks!

import cv2
import numpy as np

img = cv2.imread(pathreal, 1)
middlex = img.shape[1]/2
middley = img.shape[0]/2

def gaussianweights(image):
   newarr = [[0 for i in range(image.shape[1])] for j in range(image.shape[0])]
   for i in range(image.shape[1]):
      for j in range(image.shape[0]):
         x,y = i,j
         filtered = np.exp(((x-middlex)**2)/((middlex**2)/2)+((y-middley)**2)/((middley**2)/2))
         newarr[j][i] = image[j][i]*filtered
   return newarr

img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

weighted_img = gaussianweights(img_gray)
filtered_img = cv2.filter2D(img_gray,-1, np.array([[1,1,1,1,1],[1,1,1,1,1],[1,1,-24,1,1],[1,1,1,1,1],[1,1,1,1,1]]))
            
dst = cv2.Canny(filtered_img, 600, 800, None, 3)


lines = cv2.HoughLines(dst,1,np.pi/180,100)
for line in lines:
   for rho,theta in line:
      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(img,(x1,y1),(x2,y2),(0,0,255),2)

 cv2.imshow("Hough Image",img)
 cv2.waitKey(0)

EDIT:

Here's dst since some people asked

dst


Solution

  • With the code on OpenCV's Hough Line function I acheive this :enter image description here

    Maybe you can start from that code...