df contains all lines. (x1,y1), (x2,y2) are the endpoints. hl contains the horizontal lines only. I want to merege all horizontal lines if the gap falls under certain threshold i.e hgap.
import cv2
import pandas as pd
import numpy as np
#Read gray image
img = cv2.imread(r"C:\Users\Sachet\Desktop\LineDetection\lh.jpg",0)
_,binary = cv2.threshold(img,0,255,cv2.THRESH_OTSU)
# binary = ~binary
#Pre-processing
# kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 1))
# imgtemp = cv2.erode(binary, kernel, iterations=3)
# imgtemp = ~imgtemp
#Create default parametrization LSD
lsd = cv2.createLineSegmentDetector(0)
#Detect lines in the image
lines = lsd.detect(binary)[0] #Position 0 of the returned tuple are the detected lines
linesint = lines.astype(int)
linescolumn = lines[:,0,:]
linescolumnint = linescolumn.astype(int)
#Draw detected lines in the image
# drawn_img = lsd.drawSegments(binary,lines)
# for x1,y1,x2,y2 in linescolumnint:
# start_point = (x1,y1)
# end_point = (x2,y2)
# drawn_img = cv2.line(img, start_point, end_point, (0,0,255), 2)
cv2.imwrite(r'C:\Users\Sachet\Desktop\LineDetection\testnow.jpeg', drawn_img)
df = pd.DataFrame(linescolumnint, columns = ['x1', 'y1', 'x2', 'y2'])
#horizontal gap close
hgap = 10
hl=df.loc[df['y1'] == df['y2']]
for i in range(len(hl)):
for j in range (len(hl)):
if(hl.loc[i,'y1']==hl.loc[j,'y1'] and hl.loc[i,'x2']-hl.loc[j,'x1']<=hgap):
hl.loc[i,'x2'] = hl.loc[j,'x2']
hl.loc[j,'x1'] = hl.loc[i,'x1']
I am getting KeyError: 0. Is there any library that can help me do this? Or can someone guide me how to handle changing of the dataframe inside for loops.
Thank you.