1

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

  • 1
    It's probably easier to work with a cropped version of the image (only part of the height). That way, you have less issues with the 'vertical lines' actually being pretty bendy and not straight lines at all. – couka Dec 30 '20 at 20:28

1 Answers1

1

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()

Bilal
  • 3,191
  • 4
  • 21
  • 49
  • Hi , @bilal This is a fabric picture. Vertical thread is always present in fabrics. How can I dynamically use this solution for pictures like this ? – Bilal KAYIRAN Jan 01 '21 at 16:25
  • @BilalKAYIRAN can you provide more fabric images that this algorithm can't handle correctly, of course this solution isn't general, but I need more details and images to understand the problem perfectly. – Bilal Jan 01 '21 at 18:41
  • ok.I'll ready the images.I'll give detail with images to you.thank you for your interest @bilal – Bilal KAYIRAN Jan 02 '21 at 11:09
  • hi again @bilal :) I added two new pictures inside the subject. – Bilal KAYIRAN Jan 07 '21 at 13:50
  • @BilalKAYIRAN The code is still valid for the image before the last one with count of 72, the last image, the lines are not vertical anymore, the slope exceeds the tolerance to say "Vertical", I tell you again that this code isn't general, for different kinds of textures, you might need to change the parameter 'k', and if there was a slope above some limit in the "Vertical" lines, they will not be vertical or valid for this code anymore. – Bilal Jan 08 '21 at 08:24