def segmentation(_image, typeOfFruit):
#_denoisedImage = rank.median(_image, disk(2));
#_elevationMap = sobel(_denoisedImage);
#print(_image);
_elevationMap = sobel(_image);
#print(_image);
_marker = np.zeros_like(_image);
if (typeOfFruit == 'Counting'):
_marker[_image < 1998] = 1;
_marker[_image > 61541] = 2;
elif (typeOfFruit == 'Temperature'):
#print("Printing Image");
#print(_image < 10);
_marker[_image < 30] = 1;
#print(_marker);
_marker[_image > 150] = 2;
#_marker = rank.gradient(_denoisedImage, disk(5)) < 10;
#_marker = ndi.label(_marker)[0];
#_elevationMap = rank.gradient(_denoisedImage, disk(2));
_segmentation = watershed(_elevationMap, _marker);
#print(_segmentation);
return _segmentation;
python类watershed()的实例源码
def segmentation(_image, typeOfFruit):
#_denoisedImage = rank.median(_image, disk(2));
#_elevationMap = sobel(_denoisedImage);
#print(_image);
_elevationMap = sobel(_image);
#print(_image);
_marker = np.zeros_like(_image);
if (typeOfFruit == 'Counting'):
_marker[_image < 1998] = 1;
_marker[_image > 61541] = 2;
elif (typeOfFruit == 'Temperature'):
#print("Printing Image");
#print(_image < 10);
_marker[_image < 30] = 1;
#print(_marker);
_marker[_image > 150] = 2;
#_marker = rank.gradient(_denoisedImage, disk(5)) < 10;
#_marker = ndi.label(_marker)[0];
#_elevationMap = rank.gradient(_denoisedImage, disk(2));
_segmentation = watershed(_elevationMap, _marker);
#print(_segmentation);
return _segmentation;
def run(self, ips, snap, img, para = None):
imgs = ips.imgs
gradient = np.zeros(imgs.shape, dtype=np.float32)
gradient += ndimg.sobel(imgs, axis=0, output=np.float32)**2
gradient += ndimg.sobel(imgs, axis=1, output=np.float32)**2
gradient += ndimg.sobel(imgs, axis=2, output=np.float32)**2
gradient **= 0.5
msk = np.zeros(imgs.shape, dtype=np.uint8)
msk[imgs>para['thr2']] = 1
msk[imgs<para['thr1']] = 2
#rst = watershed(gradient, msk)
rst = watershed(gradient, msk.astype(np.uint16))
imgs[:] = (rst==1)*255
ips.lut = self.buflut
def staffline_surroundings_mask(staffline_cropobject):
"""Find the parts of the staffline's bounding box which lie
above or below the actual staffline.
These areas will be very small for straight stafflines,
but might be considerable when staffline curvature grows.
"""
# We segment both masks into "above staffline" and "below staffline"
# areas.
elevation = staffline_cropobject.mask * 255
# Blur, to plug small holes somewhat:
elevation = gaussian(elevation, sigma=1.0)
# Prepare the segmentation markers: 1 is ABOVE, 2 is BELOW
markers = numpy.zeros(staffline_cropobject.mask.shape)
markers[0, :] = 1
markers[-1, :] = 2
markers[staffline_cropobject.mask != 0] = 0
seg = watershed(elevation, markers)
bmask = numpy.ones(seg.shape)
bmask[seg != 2] = 0
tmask = numpy.ones(seg.shape)
tmask[seg != 1] = 0
return bmask, tmask
def staffline_surroundings_mask(staffline_cropobject):
"""Find the parts of the staffline's bounding box which lie
above or below the actual staffline.
These areas will be very small for straight stafflines,
but might be considerable when staffline curvature grows.
"""
# We segment both masks into "above staffline" and "below staffline"
# areas.
elevation = staffline_cropobject.mask * 255
# Blur, to plug small holes somewhat:
elevation = gaussian(elevation, sigma=1.0)
# Prepare the segmentation markers: 1 is ABOVE, 2 is BELOW
markers = numpy.zeros(staffline_cropobject.mask.shape)
markers[0, :] = 1
markers[-1, :] = 2
markers[staffline_cropobject.mask != 0] = 0
seg = watershed(elevation, markers)
bmask = numpy.ones(seg.shape)
bmask[seg != 2] = 0
tmask = numpy.ones(seg.shape)
tmask[seg != 1] = 0
return bmask, tmask
##############################################################################
def seperate_lungs(image):
#Creation of the markers as shown above:
marker_internal, marker_external, marker_watershed = generate_markers(image)
#Creation of the Sobel-Gradient
sobel_filtered_dx = ndimage.sobel(image, 1)
sobel_filtered_dy = ndimage.sobel(image, 0)
sobel_gradient = np.hypot(sobel_filtered_dx, sobel_filtered_dy)
sobel_gradient *= 255.0 / np.max(sobel_gradient)
#Watershed algorithm
watershed = morphology.watershed(sobel_gradient, marker_watershed)
#Reducing the image created by the Watershed algorithm to its outline
outline = ndimage.morphological_gradient(watershed, size=(3,3))
outline = outline.astype(bool)
#Performing Black-Tophat Morphology for reinclusion
#Creation of the disk-kernel and increasing its size a bit
blackhat_struct = [[0, 0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 1, 0, 0]]
blackhat_struct = ndimage.iterate_structure(blackhat_struct, 8)
#Perform the Black-Hat
outline += ndimage.black_tophat(outline, structure=blackhat_struct)
#Use the internal marker and the Outline that was just created to generate the lungfilter
lungfilter = np.bitwise_or(marker_internal, outline)
#Close holes in the lungfilter
#fill_holes is not used here, since in some slices the heart would be reincluded by accident
##structure = np.ones((BINARY_CLOSING_SIZE,BINARY_CLOSING_SIZE)) # 5 is not enough, 7 is
structure = morphology.disk(BINARY_CLOSING_SIZE) # better , 5 seems sufficient, we use 7 for safety/just in case
lungfilter = ndimage.morphology.binary_closing(lungfilter, structure=structure, iterations=3) #, iterations=3) # was structure=np.ones((5,5))
### NOTE if no iterattions, i.e. default 1 we get holes within lungs for the disk(5) and perhaps more
#Apply the lungfilter (note the filtered areas being assigned -2000 HU)
segmented = np.where(lungfilter == 1, image, -2000*np.ones((512, 512))) ### was -2000
return segmented, lungfilter, outline, watershed, sobel_gradient, marker_internal, marker_external, marker_watershed
def seperate_lungs_3d(image):
#Creation of the markers as shown above:
marker_internal, marker_external, marker_watershed = generate_markers_3d(image)
#Creation of the Sobel-Gradient
sobel_filtered_dx = ndimage.sobel(image, axis=2)
sobel_filtered_dy = ndimage.sobel(image, axis=1)
sobel_gradient = np.hypot(sobel_filtered_dx, sobel_filtered_dy)
sobel_gradient *= 255.0 / np.max(sobel_gradient)
#Watershed algorithm
watershed = morphology.watershed(sobel_gradient, marker_watershed)
#Reducing the image created by the Watershed algorithm to its outline
outline = ndimage.morphological_gradient(watershed, size=(1,3,3))
outline = outline.astype(bool)
#Performing Black-Tophat Morphology for reinclusion
#Creation of the disk-kernel and increasing its size a bit
blackhat_struct = [[0, 0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 1, 0, 0]]
blackhat_struct = ndimage.iterate_structure(blackhat_struct, 8)
blackhat_struct = blackhat_struct[np.newaxis,:,:]
#Perform the Black-Hat
outline += ndimage.black_tophat(outline, structure=blackhat_struct) # very long time
#Use the internal marker and the Outline that was just created to generate the lungfilter
lungfilter = np.bitwise_or(marker_internal, outline)
#Close holes in the lungfilter
#fill_holes is not used here, since in some slices the heart would be reincluded by accident
##structure = np.ones((BINARY_CLOSING_SIZE,BINARY_CLOSING_SIZE)) # 5 is not enough, 7 is
structure = morphology.disk(BINARY_CLOSING_SIZE) # better , 5 seems sufficient, we use 7 for safety/just in case
structure = structure[np.newaxis,:,:]
lungfilter = ndimage.morphology.binary_closing(lungfilter, structure=structure, iterations=3) #, iterations=3) # was structure=np.ones((5,5))
### NOTE if no iterattions, i.e. default 1 we get holes within lungs for the disk(5) and perhaps more
#Apply the lungfilter (note the filtered areas being assigned -2000 HU)
segmented = np.where(lungfilter == 1, image, -2000*np.ones(marker_internal.shape))
return segmented, lungfilter, outline, watershed, sobel_gradient, marker_internal, marker_external, marker_watershed
def seperate_lungs(image):
#Creation of the markers as shown above:
marker_internal, marker_external, marker_watershed = generate_markers(image)
#Creation of the Sobel-Gradient
sobel_filtered_dx = ndimage.sobel(image, 1)
sobel_filtered_dy = ndimage.sobel(image, 0)
sobel_gradient = np.hypot(sobel_filtered_dx, sobel_filtered_dy)
sobel_gradient *= 255.0 / np.max(sobel_gradient)
#Watershed algorithm
watershed = morphology.watershed(sobel_gradient, marker_watershed)
#Reducing the image created by the Watershed algorithm to its outline
outline = ndimage.morphological_gradient(watershed, size=(3,3))
outline = outline.astype(bool)
#Performing Black-Tophat Morphology for reinclusion
#Creation of the disk-kernel and increasing its size a bit
blackhat_struct = [[0, 0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 1, 0, 0]]
blackhat_struct = ndimage.iterate_structure(blackhat_struct, 8)
#Perform the Black-Hat
outline += ndimage.black_tophat(outline, structure=blackhat_struct)
#Use the internal marker and the Outline that was just created to generate the lungfilter
lungfilter = np.bitwise_or(marker_internal, outline)
#Close holes in the lungfilter
#fill_holes is not used here, since in some slices the heart would be reincluded by accident
##structure = np.ones((BINARY_CLOSING_SIZE,BINARY_CLOSING_SIZE)) # 5 is not enough, 7 is
structure = morphology.disk(BINARY_CLOSING_SIZE) # better , 5 seems sufficient, we use 7 for safety/just in case
lungfilter = ndimage.morphology.binary_closing(lungfilter, structure=structure, iterations=3) #, iterations=3) # was structure=np.ones((5,5))
### NOTE if no iterattions, i.e. default 1 we get holes within lungs for the disk(5) and perhaps more
#Apply the lungfilter (note the filtered areas being assigned -2000 HU)
segmented = np.where(lungfilter == 1, image, -2000*np.ones((512, 512))) ### was -2000
return segmented, lungfilter, outline, watershed, sobel_gradient, marker_internal, marker_external, marker_watershed
def seperate_lungs_3d(image):
#Creation of the markers as shown above:
marker_internal, marker_external, marker_watershed = generate_markers_3d(image)
#Creation of the Sobel-Gradient
sobel_filtered_dx = ndimage.sobel(image, axis=2)
sobel_filtered_dy = ndimage.sobel(image, axis=1)
sobel_gradient = np.hypot(sobel_filtered_dx, sobel_filtered_dy)
sobel_gradient *= 255.0 / np.max(sobel_gradient)
#Watershed algorithm
watershed = morphology.watershed(sobel_gradient, marker_watershed)
#Reducing the image created by the Watershed algorithm to its outline
outline = ndimage.morphological_gradient(watershed, size=(1,3,3))
outline = outline.astype(bool)
#Performing Black-Tophat Morphology for reinclusion
#Creation of the disk-kernel and increasing its size a bit
blackhat_struct = [[0, 0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 1, 0, 0]]
blackhat_struct = ndimage.iterate_structure(blackhat_struct, 8)
blackhat_struct = blackhat_struct[np.newaxis,:,:]
#Perform the Black-Hat
outline += ndimage.black_tophat(outline, structure=blackhat_struct) # very long time
#Use the internal marker and the Outline that was just created to generate the lungfilter
lungfilter = np.bitwise_or(marker_internal, outline)
#Close holes in the lungfilter
#fill_holes is not used here, since in some slices the heart would be reincluded by accident
##structure = np.ones((BINARY_CLOSING_SIZE,BINARY_CLOSING_SIZE)) # 5 is not enough, 7 is
structure = morphology.disk(BINARY_CLOSING_SIZE) # better , 5 seems sufficient, we use 7 for safety/just in case
structure = structure[np.newaxis,:,:]
lungfilter = ndimage.morphology.binary_closing(lungfilter, structure=structure, iterations=3) #, iterations=3) # was structure=np.ones((5,5))
### NOTE if no iterattions, i.e. default 1 we get holes within lungs for the disk(5) and perhaps more
#Apply the lungfilter (note the filtered areas being assigned -2000 HU)
segmented = np.where(lungfilter == 1, image, -2000*np.ones(marker_internal.shape))
return segmented, lungfilter, outline, watershed, sobel_gradient, marker_internal, marker_external, marker_watershed
individual_N2_X_Y_cluster_stage_watershed.py 文件源码
项目:CElegansBehaviour
作者: ChristophKirst
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
def makeSegmentation(d, s, nbins = 256, verbose = True, sigma = 0.75, min_distance = 1):
fn = os.path.join(datadir, 'data_stage%d_%s.npy' % (s,features[0]));
dists = np.load(fn);
fn = os.path.join(datadir, 'data_stage%d_%s.npy' % (s,features[1]));
rots = np.load(fn);
ddata = np.vstack([np.log(dists[:,d]), (rots[:,d])]).T
#gmmdata = np.vstack([dists[:,j], (rots[:,j])]).T
#ddata.shape
nanids = np.logical_or(np.any(np.isnan(ddata), axis=1), np.any(np.isinf(ddata), axis=1));
ddata = ddata[~nanids,:];
#ddata.shape
imgbin = None;
img2 = smooth(ddata, nbins = [nbins, nbins], sigma = (sigma,sigma))
#img = smooth(ddata, nbins = [nbins, nbins], sigma = (1,1))
local_maxi = peak_local_max(img2, indices=False, min_distance = min_distance)
imgm2 = img2.copy();
imgm2[local_maxi] = 3 * imgm2.max();
if verbose:
imgbin = smooth(ddata, nbins = [nbins, nbins], sigma = None)
plt.figure(220); plt.clf()
plt.subplot(2,2,1)
plt.imshow(imgbin)
plt.subplot(2,2,2)
plt.imshow(img2)
plt.subplot(2,2,3);
plt.imshow(imgm2, cmap=plt.cm.jet, interpolation='nearest')
markers = ndi.label(local_maxi)[0]
labels = watershed(-img2, markers, mask = None);
print "max labels: %d" % labels.max()
if verbose:
fig, axes = plt.subplots(ncols=3, sharex=True, sharey=True, subplot_kw={'adjustable':'box-forced'})
ax0, ax1, ax2 = axes
ax0.imshow(img2, cmap=plt.cm.jet, interpolation='nearest')
ax0.set_title('PDF')
labels[imgbin==0] = 0;
labels[0,0] = -1;
ax1.imshow(labels, cmap=plt.cm.rainbow, interpolation='nearest')
ax1.set_title('Segmentation on Data')
#labelsws[0,0] = -1;
#ax2.imshow(labelsws, cmap=plt.cm.rainbow, interpolation='nearest')
#ax1.set_title('Segmentation Full')
return labels;
#classification for a specific work based on the segmentation above
def get_segmented_lungs(image):
#Creation of the markers as shown above:
marker_internal, marker_external, marker_watershed = generate_markers(image)
#Creation of the Sobel-Gradient
sobel_filtered_dx = ndimage.sobel(image, 1)
sobel_filtered_dy = ndimage.sobel(image, 0)
sobel_gradient = np.hypot(sobel_filtered_dx, sobel_filtered_dy)
sobel_gradient *= 255.0 / np.max(sobel_gradient)
#Watershed algorithm
watershed = morphology.watershed(sobel_gradient, marker_watershed)
#Reducing the image created by the Watershed algorithm to its outline
outline = ndimage.morphological_gradient(watershed, size=(3,3))
outline = outline.astype(bool)
#Performing Black-Tophat Morphology for reinclusion
#Creation of the disk-kernel and increasing its size a bit
blackhat_struct = [[0, 0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 1, 0, 0]]
#blackhat_struct = ndimage.iterate_structure(blackhat_struct, 8)
blackhat_struct = ndimage.iterate_structure(blackhat_struct, 14) # <- retains more of the area, 12 works well. Changed to 14, 12 still excluded some parts.
#Perform the Black-Hat
outline += ndimage.black_tophat(outline, structure=blackhat_struct)
#Use the internal marker and the Outline that was just created to generate the lungfilter
lungfilter = np.bitwise_or(marker_internal, outline)
#Close holes in the lungfilter
#fill_holes is not used here, since in some slices the heart would be reincluded by accident
lungfilter = ndimage.morphology.binary_closing(lungfilter, structure=np.ones((5,5)), iterations=3)
#Apply the lungfilter (note the filtered areas being assigned threshold_min HU)
segmented = np.where(lungfilter == 1, image, threshold_min*np.ones(image.shape))
#return segmented, lungfilter, outline, watershed, sobel_gradient, marker_internal, marker_external, marker_watershed
return segmented
def get_segmented_lungs(image):
#Creation of the markers as shown above:
marker_internal, marker_external, marker_watershed = generate_markers(image)
#Creation of the Sobel-Gradient
sobel_filtered_dx = ndimage.sobel(image, 1)
sobel_filtered_dy = ndimage.sobel(image, 0)
sobel_gradient = np.hypot(sobel_filtered_dx, sobel_filtered_dy)
sobel_gradient *= 255.0 / np.max(sobel_gradient)
#Watershed algorithm
watershed = morphology.watershed(sobel_gradient, marker_watershed)
#Reducing the image created by the Watershed algorithm to its outline
outline = ndimage.morphological_gradient(watershed, size=(3,3))
outline = outline.astype(bool)
#Performing Black-Tophat Morphology for reinclusion
#Creation of the disk-kernel and increasing its size a bit
blackhat_struct = [[0, 0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 1, 0, 0]]
#blackhat_struct = ndimage.iterate_structure(blackhat_struct, 8)
blackhat_struct = ndimage.iterate_structure(blackhat_struct, 14) # <- retains more of the area, 12 works well. Changed to 14, 12 still excluded some parts.
#Perform the Black-Hat
outline += ndimage.black_tophat(outline, structure=blackhat_struct)
#Use the internal marker and the Outline that was just created to generate the lungfilter
lungfilter = np.bitwise_or(marker_internal, outline)
#Close holes in the lungfilter
#fill_holes is not used here, since in some slices the heart would be reincluded by accident
lungfilter = ndimage.morphology.binary_closing(lungfilter, structure=np.ones((5,5)), iterations=3)
#Apply the lungfilter (note the filtered areas being assigned threshold_min HU)
segmented = np.where(lungfilter == 1, image, threshold_min*np.ones(image.shape))
#return segmented, lungfilter, outline, watershed, sobel_gradient, marker_internal, marker_external, marker_watershed
return segmented
def get_segmented_lungs(image):
#Creation of the markers as shown above:
marker_internal, marker_external, marker_watershed = generate_markers(image)
#Creation of the Sobel-Gradient
sobel_filtered_dx = ndimage.sobel(image, 1)
sobel_filtered_dy = ndimage.sobel(image, 0)
sobel_gradient = np.hypot(sobel_filtered_dx, sobel_filtered_dy)
sobel_gradient *= 255.0 / np.max(sobel_gradient)
#Watershed algorithm
watershed = morphology.watershed(sobel_gradient, marker_watershed)
#Reducing the image created by the Watershed algorithm to its outline
outline = ndimage.morphological_gradient(watershed, size=(3,3))
outline = outline.astype(bool)
#Performing Black-Tophat Morphology for reinclusion
#Creation of the disk-kernel and increasing its size a bit
blackhat_struct = [[0, 0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 1, 0, 0]]
#blackhat_struct = ndimage.iterate_structure(blackhat_struct, 8)
blackhat_struct = ndimage.iterate_structure(blackhat_struct, 14) # <- retains more of the area, 12 works well. Changed to 14, 12 still excluded some parts.
#Perform the Black-Hat
outline += ndimage.black_tophat(outline, structure=blackhat_struct)
#Use the internal marker and the Outline that was just created to generate the lungfilter
lungfilter = np.bitwise_or(marker_internal, outline)
#Close holes in the lungfilter
#fill_holes is not used here, since in some slices the heart would be reincluded by accident
lungfilter = ndimage.morphology.binary_closing(lungfilter, structure=np.ones((5,5)), iterations=3)
#Apply the lungfilter (note the filtered areas being assigned threshold_min HU)
segmented = np.where(lungfilter == 1, image, threshold_min*np.ones(image.shape))
#return segmented, lungfilter, outline, watershed, sobel_gradient, marker_internal, marker_external, marker_watershed
return segmented