问题
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:
This is the 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.
回答1:
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:
Output:
来源:https://stackoverflow.com/questions/46281623/delete-segmented-lines-opencv-python