'Count lines in image

I am planning to use Opencv on Raspberry pi 3 with camera to count lines in the following image enter image description here

It will be used in machine which produce threads. If one (or more) will be lost it will stop the machine.

Now i am wondering how to do that...?

  1. I will do a loop to capture the images
  2. I will crop the images to see only the part with lines
  3. I will convert it to black&white
  4. how to count them ? in a loop - check pixel value change? Or there is a better/faster idea?

Thank you for advice!

EDIT

P.S. I used cv2.findContours (answer from Jeru Luke). I've putted an A4 sheet with black lines in front of camera. I works ok in while loop BUT... i have 43 lines on sheet. When camera detects some differences i wrote the results to file. Sometimes i have 710,800,67 etc.

Pls look on file with values i have https://www.dropbox.com/s/jnn4w8mq3rrtppo/bledy.txt?dl=0

lines....The error is permanet for some few secounds. Tere is noting wronge when i have 43,43,43,43,44,43,43,43 (the one is wrong) because i watch few values before i put error. But when the are hundreds of bad values i have no idea...



Solution 1:[1]

I have something relatively simpler. It does not involve any for loops hence requires less time. I used the concept of counting the contours in the image after finding an appropriate threshold. I found the perfect threshold through trial-and-error.

I have the approach in python:

import cv2

path = 'C:/Users/Desktop/stack/contour/'
img = cv2.imread(path + 'lines.png', 0)
cv2.imshow('original Image', img)

ret, thresh = cv2.threshold(img, 80, 255, cv2.THRESH_BINARY_INV)
cv2.imshow('thresh1', thresh)

_, contours, hierarchy =    cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print('Number of lines:', len(contours))

cv2.waitKey(0)
cv2.destroyAllWindows()

Note:

  1. As you can see there are no for loops involved. There is no need to count the number of pixel changes as well. Each presumed line becomes a contour. Using `len(contours) you get the number of lines present.
  2. Using Hough Line transform would work well only If the lines are straight. Since the lines in the provided image are slanted it won't find perfect lines. This statement is more emphasized in the comments by @MarkSetchell.

Solution 2:[2]

Use Hough Lines Transform to detect the lines and just count the number of countours you find.

Here there's a tutorial for your problem (since you didn't specify the Language, this is in python).

OpenCV Tutorial Hough Lines

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Jeru Luke