Wolfmercury
Wolfmercury

Reputation: 124

Finding lines in filtered image with OpenCV

Edit: Added Gaussian Blur, but it does not really help.

I'm trying to obtain the in the following image visible lines of a captured grid: 8-bit image of the grid

I already tried to use cv2/OpenCV but failed to derive proper lines, but maybe more experienced users might have ideas how to capture the lines. My used, simple code (matrix is a 2d nd.array in greyscale):

import numpy as np
import matplotlib.pyplot as plt
import cv2

fig, (ax1,ax2) = plt.subplots(2,2,figsize=(12,12))

matrix = cv2.GaussianBlur(matrix,(3,3),0)

ax1[0].imshow(matrix)
ax1[0].set_title("Original")

matrix = np.array(matrix,dtype=np.uint8)
    
tresh1, tresh2 = 70, 110    #the thresholds for the hysteresis procedure
edges = cv2.Canny(matrix,tresh1,tresh2,apertureSize=3)
ax1[1].imshow(edges)
ax1[1].set_title("Canny-Edges")

im = matrix
lines = cv2.HoughLines(edges,1,np.pi/180,50)
if lines is not None:
    for i in range(len(lines)):
        rho = lines[i][0][0]
        theta = lines[i][0][1]
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a * rho
        y0 = b * rho
        pt1 = (int(x0 + 1000*(-b)), int(y0 + 1000*(a)))
        pt2 = (int(x0 - 1000*(-b)), int(y0 - 1000*(a)))
        #print(pt1, pt2)
        cv2.line(im, pt1, pt2, (0,0,255), 2, cv2.LINE_AA)

ax2[0].imshow(im)
ax2[0].set_title("Lines")

which results in (mind the lower right little area of action in the third "Lines" image): enter image description here Now, I have played with the thresholds and the line parameters (for this example I reset them to the one I found to be the default ones) but never got near of the vertical line of the original. Do you have advise?

If needed I can provide a numpy.savetxt file of the original image

Upvotes: 0

Views: 153

Answers (1)

AltunE
AltunE

Reputation: 410

Actually, I haven't quite understood what are you looking for but maybe Gabor Filter fixes your problem. Maybe you could get the best output by playing with the values I put in the "kernel" (they are too sensitive).

import cv2
import numpy as np
ksize=12
sigma=18
theta=1*np.pi/1
lamda=1*np.pi/1
gamma=0.5
phi=0

kernel=cv2.getGaborKernel((ksize,ksize),sigma,theta,lamda,gamma,
                                                          phi,ktype=cv2.CV_32F)

img=cv2.imread("originalImage.jpg") #your image: https://i.sstatic.net/uMxaV.png
img = cv2.GaussianBlur(img,(3,3),0)

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

fmig=cv2.filter2D(img,cv2.CV_8UC3,kernel)
#CV_8UC3 == uint8

kernel_resize=cv2.resize(kernel,(400,400))

cv2.imshow("gabor",fmig)

cv2.imshow("gaborkernel",kernel_resize)
cv2.waitKey(0)

Output image

Upvotes: 1

Related Questions