1

I am trying to count seeds in an image using cv2 thresholding. The test image is below: single seed

When I run the below code to create a mask:

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

img = cv2.imread('S__14278933.jpg')
#img = cv2.fastNlMeansDenoisingColored(img,None,10,10,7,21)

mask = cv2.threshold(img[:, :, 0], 255, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
plt.imshow(mask)

I get the following mask:

mask

But ideally it should give a small yellow dot at the centre. I have tried this with other images and it works just fine.

Can someone help?

vaisxn
  • 71
  • 8

2 Answers2

2

The lighting in your image seems not uniform. Try using Adaptive Thresholding:

import cv2
import numpy as np

# image path
path = "D://opencvImages//"
fileName = "c6pBO.jpg"

# Reading an image in default mode:
inputImage = cv2.imread(path + fileName)

# Convert the image to grayscale:
grayImage = cv2.cvtColor(inputImage, cv2.COLOR_BGR2GRAY)

# Get binary image via Adaptive Thresholding :
windowSize = 31
windowConstant = 40
binaryImage = cv2.adaptiveThreshold( grayImage, 255, cv2.ADAPTIVE_THRESH_MEAN_C, 
                                     cv2.THRESH_BINARY_INV, windowSize, windowConstant )

cv2.imshow("binaryImage", binaryImage)
cv2.waitKey(0)

enter image description here

You might want to apply an Area Filter after this, though, as dark portions on the image will yield noise.

stateMachine
  • 5,227
  • 4
  • 13
  • 29
0

Try it

img=cv2.imread('foto.jpg',0)
mask = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV )[1]
Leox
  • 340
  • 4
  • 9