Save binary image after watershed
<p>I have problems storing my image after watershed segmentation as a binary image. When I plot the segmentation with cmap=plt.cm.gray it shows a binary image but I don't know how to store the image (without to display it).</p>

<pre><code>import cv2
import numpy as np
from matplotlib import pyplot as plt
from skimage.morphology import watershed
from scipy import ndimage as ndi
from skimage import morphology
from skimage.filters import sobel
from skimage.io import imread, imsave, imshow
import scipy.misc

img = cv2.imread('07.png')
img = cv2.medianBlur(img,5)
b,g,r = cv2.split(img)

elevation_map = sobel(r)
markers = np.zeros_like(r)
markers[s &lt; 140] = 1
markers[s &gt; 200] = 2
segmentation = morphology.watershed(elevation_map, markers)

fig, ax = plt.subplots(figsize=(4, 3))
ax.imshow(segmentation, cmap=plt.cm.gray, interpolation='nearest')
ax.axis('off')
plt.show()
</code></pre>

<p>In short, you can save it similarly to how you are displaying it using (see <a href="http://stackoverflow.com/questions/30941350/how-are-images-actually-saved-with-skimage-python">here</a> for reference):</p>

<pre><code>plt.imsave('test.png', segmentation, cmap = plt.cm.gray)
</code></pre>

<p>Note however, that <code>segmentation</code> will consist of two labels, label <code>1</code> and label <code>2</code>. This is because you are setting up</p>

<pre><code>markers[s &lt; 140] = 1
markers[s &gt; 200] = 2
</code></pre>

<p>which leaves a region where <code>markers</code> is zero; those pixels are not treated as markes. The result of running <code>watershed</code> is a label matrix consisting of the marker labels, in your case <code>1</code> and <code>2</code>. When displaying it using your code, you will see a binary image because <code>cmap = plt.cm.gray</code> will scale the image. As the label <code>0</code> does not exist, it will scale label <code>1</code> to value <code>0</code> (i.e. black) and label <code>2</code> to value <code>255</code> (i.e. white) (see <a href="http://stackoverflow.com/questions/12760797/imshowimg-cmap-cm-gray-shows-a-white-for-128-value">here</a> for explanation and example). The same is done when using <code>plt.imsave</code> with <code>cmap = plt.cm.gray</code>. Long story short, if you want to save the image using any other method/library (for example OpenCV), you might need to do something like this:</p>

<pre><code>segmentation[segmentation == 1] == 0
segmentation[segmentation == 2] == 255
segmentation = segmentation.astype(np.uint8)
# e.g. when writing using OpenCV
cv2.imwrite('test.png', segmentation)
</code></pre>

python image-segmentation watershed skimage