How can i subtract the background from an image in mahotas and opencv in python?

微笑、不失礼 提交于 2019-12-13 08:29:21

问题


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?


回答1:


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)



回答2:


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



来源:https://stackoverflow.com/questions/21152497/how-can-i-subtract-the-background-from-an-image-in-mahotas-and-opencv-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!