Question

I have many image like this or like this and i use this code:

fork = mh.imread(path)
bin = fork[:,:,0]
bin = mh.erode(bin)
bin = (bin < 80)

for the 2nd image, but i have to use this:

bin = (bin < 127)

for the first.

There is a way for automatically obtain a good image without background, or i have to choose a median value hopefully is good for the most of my images?

Was it helpful?

Solution

There is a threshold value that is called "Otsu Threshold". Here you have more information.

You can use otsu to do it in Mahotas or threshold_otsu in scikit-image:

fork = mh.imread(path)
bin = fork[:,:,0]
thresh = mh.otsu(bin)
binary =( bin< thresh)

OTHER TIPS

I understand that you want to separate the white background from the image. Here are the steps to do this. I will write in plain English, because I am not familiar with python.

1: Calculate closing of the image (application of dilation and than erosion). Use structural element as square of size 5x5 for dilation and erosion.

C = mh.dilate(bin)
C = mh.erode(C);

This will give you the background

2: Subtract the background from the original image:

C = C-bin

This will give you an image of the star painted in white and the background is black

3: Now calculate automatic threshold for binarization. Use simple Otsu technique to estimate the best threshold. In openCV this is something like:

double thresh = cv::threshold(im,im,0,255,CV_THRESH_BINARY | CV_THRESH_OTSU);
cv::threshold(im,im,thresh,255,CV_THRESH_BINARY_INV);

This will give you perfect results for your images. Do not try to guess the threshold. It is not 80 and not 127 for your images. Use Otsu

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top