Reputation: 2520
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).
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 < 140] = 1
markers[s > 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()
Upvotes: 0
Views: 1285
Reputation: 2618
In short, you can save it similarly to how you are displaying it using (see here for reference):
plt.imsave('test.png', segmentation, cmap = plt.cm.gray)
Note however, that segmentation
will consist of two labels, label 1
and label 2
. This is because you are setting up
markers[s < 140] = 1
markers[s > 200] = 2
which leaves a region where markers
is zero; those pixels are not treated as markes. The result of running watershed
is a label matrix consisting of the marker labels, in your case 1
and 2
. When displaying it using your code, you will see a binary image because cmap = plt.cm.gray
will scale the image. As the label 0
does not exist, it will scale label 1
to value 0
(i.e. black) and label 2
to value 255
(i.e. white) (see here for explanation and example). The same is done when using plt.imsave
with cmap = plt.cm.gray
. 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:
segmentation[segmentation == 1] == 0
segmentation[segmentation == 2] == 255
segmentation = segmentation.astype(np.uint8)
# e.g. when writing using OpenCV
cv2.imwrite('test.png', segmentation)
Upvotes: 1