MATLAB: How to get the threshold automatically when converting image from hsv to bw

image processingImage Processing Toolbox

Hi! I have to convert my image from HSV to BW to do all the analysis. But I have a lot of images and I can't adjust the threshold one by one. I have checked some of my images, and the threshold change from 0.1 to 0.4. SO the change is quite large and I can't use a single threshold for all the image.
So does somebody know how can I generate the threshold for each image without manually checking the histogram? I need to choose the threshold after the first pick in the histgram.
Some of my codes are here:
b=imread('test4.jpg')
hsvIm = rgb2hsv(b) % convert the image to hsv format
imshow(hsvIm)
histogram(hsvIm(:,:,1))
%thresholding on the hue space
bwIm = hsvIm(:,:,1) < 0.3 % the threshold can change from 0.1 to 0.4
I also attach some pictures here:
Thank you in advance!!!

Best Answer

Hmm, I just want to update my question here.
Finally, I don't need to set the threshold separately for each image. I just converted the image from RGB to HSV and then to YCBCR. After the second conversion, the threshold for YCBCR to BW is more or less the same for every image, no matter how different the colony color and size. I'm not really sure whether it is proper to do two conversions. But at least it works.
I also tried to convert RGB directly to YCBCR, but the result is not as good as through two conversions.
The only problem that I still have is that imfindcircles() on bw image doesn't really work well even though I played with the sensitivity and EdgeThreshold, and I don't know why. Do somebody know the possible reason?