2

Given the followig code:

import numpy as np
import cv2

gray = cv2.imread('image.png')
edges = cv2.Canny(gray,50,150,apertureSize = 3)
cv2.imwrite('edges-50-150.jpg',edges)
minLineLength=100
lines = cv2.HoughLinesP(image=edges,rho=1,theta=np.pi/180, threshold=100,lines=np.array([]), minLineLength=minLineLength,maxLineGap=80)

a,b,c = lines.shape
for i in range(a):
    cv2.line(gray, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 1, cv2.LINE_AA)
    cv2.imwrite('houghlines.jpg', gray)
    cv2.imshow('img', gray)
    cv2.waitKey(0)

I can achieve the horizontal lines that there are in this (source) image:

src

This is the result:

result

How can I delete the lines which are in red ? What I want to achieve is to delete these lines so the image is more clean and ready to use by another process. The code has been taken from here.

lucians
  • 2,239
  • 5
  • 36
  • 64

1 Answers1

5

Check this link http://docs.opencv.org/3.2.0/d1/dee/tutorial_moprh_lines_detection.html and detect horizontal lines.Then, Set pixel values to zero containing horizontal lines. Given code is in C++ but you can easily convert it into Python.

You can also reject horizontal lines from your detected lines using slope of lines. Exclude all the lines having slope almost equal to zero.

Following is the code snippet you can use (I made little changes in your code based on slope and morphological closing):

import numpy as np
import cv2

gray = cv2.imread('image.png')
edges = cv2.Canny(gray,50,150,apertureSize = 3)
cv2.imwrite('edges-50-150.jpg',edges)
minLineLength=100
lines = cv2.HoughLinesP(image=edges,rho=1,theta=np.pi/180, threshold=100,lines=np.array([]), minLineLength=minLineLength,maxLineGap=80)

a,b,c = lines.shape
for i in range(a):
    x = lines[i][0][0] - lines [i][0][2]
    y = lines[i][0][1] - lines [i][0][3]
    if x!= 0:
        if abs(y/x) <1:
            cv2.line(gray, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (255, 255, 255), 1, cv2.LINE_AA)

se = cv2.getStructuringElement(cv2.MORPH_ELLIPSE , (3,3))
gray = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, se)
cv2.imwrite('houghlines.jpg', gray)
cv2.imshow('img', gray)
cv2.waitKey(0)

Input:

input

Output:

output

Jazz
  • 916
  • 1
  • 8
  • 22
  • Already used the code converted in Python. It's [here](https://stackoverflow.com/questions/46274961/removing-horizontal-lines-in-image-opencv-pyhton-matplotlib?noredirect=1#comment79515464_46274961) – lucians Sep 18 '17 at 14:48
  • I have edited my answer. If you have not obtained result using morphological operations, then try to exclude lines based on slope. – Jazz Sep 18 '17 at 14:51
  • I have added code snippet to my answer. If your problem is not solved, you can check this. – Jazz Sep 19 '17 at 02:35