title: How to detect (Count) Hair from image using OpenCV?
body: <p>I have try below code using <code>OpenCV</code> functions <code>cvtColor</code>,<code>Canny</code> and <code>HoughLinesP</code> but not able to get accurate result or not work in some cases.</p>
  
  <pre><code>private boolean opencvProcessCount(Uri picFileUri) {
  hairCount = 0;
  totalC = 0;
  //Log.e("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;","count " + picFileUri);
  try {
      InputStream iStream = getContentResolver().openInputStream(picFileUri);
      byte[] im = getBytes(iStream);
      BitmapFactory.Options opt = new BitmapFactory.Options();
      opt.inDither = true;
      opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
      Bitmap image = BitmapFactory.decodeByteArray(im, 0, im.length);
  
      Mat mYuv = new Mat();
      Utils.bitmapToMat(image, mYuv);
      Mat mRgba = new Mat();
      Imgproc.cvtColor(mYuv, mRgba, Imgproc.COLOR_RGB2GRAY, 4);
      Imgproc.Canny(mRgba, mRgba, 80, 90);
      Mat lines = new Mat();
      int threshold = 80;
      int minLineSize = 30;
      int lineGap = 100;
  
      Imgproc.HoughLinesP(mRgba, lines, 1, Math.PI/180, threshold, minLineSize, lineGap);
  
      for (int x = 0; x &lt; lines.rows(); x++)
      {
          double[] vec = lines.get(x, 0);
          double x1 = vec[0],
                  y1 = vec[1],
                  x2 = vec[2],
                  y2 = vec[3];
          Point start = new Point(x1, y1);
          Point end = new Point(x2, y2);
          double dx = x1 - x2;
          double dy = y1 - y2;
  
          double dist = Math.sqrt (dx*dx + dy*dy);
          totalC ++;
          Log.e("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;","dist " + dist);
          if(dist&gt;300.d)
          {
              hairCount ++;
              // Log.e("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;","count " + x);
              Imgproc.line(mRgba, start, end, new Scalar(0,255, 0, 255),5);// here initimg is the original image.
          }// show those lines that have length greater than 300
  
  
      }
  
      Log.e("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;",totalC+" out hairCount " + hairCount);
  
      // Imgproc.
  } catch (Throwable e) {
      // Log.e("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;","count " + e.getMessage());
      e.printStackTrace();
  }
  return false;
  }
  </code></pre>
  
  <p>Below are sample images to count hair :</p>
  
  <p><a href="https://i.stack.imgur.com/j0npD.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/j0npD.jpg" alt="enter image description here"></a></p>
  
  <p><a href="https://i.stack.imgur.com/m7ASM.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/m7ASM.jpg" alt="enter image description here"></a></p>