Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
934 views
in Technique[技术] by (71.8m points)

How can I find vertical lines in the image? (Opencv and Python) Total vertical avalanche needs fine

Hi Everyone,

I need mark the vertical lines in the picture and find the number.In the example I have done below, I cannot mark exactly.So I find the number of vertical lines wrong.I should draw the lines straight but I couldn't draw Where could I be wrong ?

enter image description here

the result ? found(Wrong) print(len(contours)) 25 Correct Result = (22)

import cv2
import numpy as np
from matplotlib import pyplot as plt
# Functions

def resizewithAspectRatio(img,width=None,height=None):
    return cv2.resize(img,(width,height),cv2.INTER_LINEAR)


#------------------------

img=resizewithAspectRatio(cv2.imread("1.jpg"),640,640)
gray_img=resizewithAspectRatio(cv2.cvtColor(img,cv2.COLOR_BGR2GRAY),640,640) 

empty_img=np.zeros((640,640),np.uint8)+255
kernel = np.ones((5,5),np.uint8)
kernel_size = (3,3)
#Apply Filter

gray_img=cv2.medianBlur(gray_img,3)
gray_img = cv2.bilateralFilter(gray_img,9,75,75)


#--------------------------

threshold = cv2.adaptiveThreshold(gray_img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
            cv2.THRESH_BINARY_INV,83,3)


Reverse_img=np.where(threshold==255, 0, 
         (np.where(threshold==0, 255, threshold)))



closing = cv2.morphologyEx(Reverse_img, cv2.MORPH_CLOSE, kernel,iterations=2)


edges = cv2.Canny(closing,50,150,apertureSize = 3)
linesP = cv2.HoughLinesP(edges, 1, np.pi / 180, 50, None, 1, 100)
    
if linesP is not None:
    for i in range(0, len(linesP)):
        l = linesP[i][0]
        cv2.line(empty_img, (l[0], l[2]), (l[3], l[4]), (0,0,255), 4, cv2.LINE_AA)





cv2.imshow("?M",empty_img)


contours,hierarchy=cv2.findContours(empty_img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
print(len(contours))



titles=['Org_Img','threshold','Reverse_img','closing','empty_img']
images=[img,threshold,Reverse_img,closing,empty_img]
for i in range(5):
    plt.subplot(3,3,i+1),plt.imshow(images[i] , 'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])
    
plt.show()

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Please see my other answer for further explanation.

Result

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

# Read image
img = cv2.imread('input.jpg', 0)

# #------------------------
# # Morphology
# #========================
# # Closing
# #------------------------
closed = cv2.morphologyEx(img, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_RECT, (1, 7)))

# #------------------------
# # Statistics
# #========================
dens = np.sum(img, axis=0)
mean = np.mean(dens)

#------------------------
# Thresholding
#========================
thresh = 255 * np.ones_like(img)
k = 0.9
for idx, val in enumerate(dens):
    if val< k*mean:
        thresh[:,idx] = 0

thresh = 255 - thresh
contours,hierarchy=cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
count = len(contours)


#------------------------
# plotting the results
#========================
plt.figure(num='{} Lines'.format(count))

plt.subplot(221)
plt.imshow(img, cmap='gray')
plt.title('Original')
plt.axis('off')

plt.subplot(223)
plt.imshow(thresh, cmap='gray')
plt.title('Thresholded')
plt.axis('off')

plt.subplot(224)
plt.imshow((thresh/255)*img, cmap='gray')
plt.title('Result')
plt.axis('off')

plt.subplot(222)
plt.hist(dens)
plt.axvline(dens.mean(), color='k', linestyle='dashed', linewidth=1)
plt.title('dens hist')

plt.show()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...