本文整理汇总了Python中skimage.segmentation.slic函数的典型用法代码示例。如果您正苦于以下问题:Python slic函数的具体用法?Python slic怎么用?Python slic使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了slic函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: slics_3D
def slics_3D(im, pseudo_3D=True, n_segments=100, get_slicewise=False):
if im.ndim != 3:
raise Exception('3D image is needed.')
if not pseudo_3D:
# need to convert to RGB image
im_rgb = np.zeros((im.shape[0], im.shape[1], im.shape[2], 3))
im_rgb[:,:,:,0] = im
im_rgb[:,:,:,1] = im
im_rgb[:,:,:,2] = im
suppxls = skiseg.slic(im_rgb, n_segments=n_segments, spacing=(2,1,1))
else:
suppxls = np.zeros(im.shape)
if get_slicewise:
suppxls_slicewise = np.zeros(im.shape)
offset = 0
for i in range(im.shape[0]):
# suppxl = skiseg.slic(cv2.cvtColor(im[i,:,:], cv2.COLOR_GRAY2RGB), n_segments=n_segments)
suppxl = skiseg.slic(skicol.gray2rgb(im[i,:,:]), n_segments=n_segments)
suppxls[i,:,:] = suppxl + offset
if get_slicewise:
suppxls_slicewise[i,:,:] = suppxl
offset = suppxls.max() + 1
if get_slicewise:
return suppxls, suppxls_slicewise
else:
return suppxls
示例2: test_enforce_connectivity
def test_enforce_connectivity():
img = np.array([[0, 0, 0, 1, 1, 1],
[1, 0, 0, 1, 1, 0],
[0, 0, 0, 1, 1, 0]], np.float)
segments_connected = slic(img, 2, compactness=0.0001,
enforce_connectivity=True,
convert2lab=False)
segments_disconnected = slic(img, 2, compactness=0.0001,
enforce_connectivity=False,
convert2lab=False)
# Make sure nothing fatal occurs (e.g. buffer overflow) at low values of
# max_size_factor
segments_connected_low_max = slic(img, 2, compactness=0.0001,
enforce_connectivity=True,
convert2lab=False, max_size_factor=0.8)
result_connected = np.array([[0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 1, 1]], np.float)
result_disconnected = np.array([[0, 0, 0, 1, 1, 1],
[1, 0, 0, 1, 1, 0],
[0, 0, 0, 1, 1, 0]], np.float)
assert_equal(segments_connected, result_connected)
assert_equal(segments_disconnected, result_disconnected)
assert_equal(segments_connected_low_max, result_connected)
示例3: test_spacing
def test_spacing():
rnd = np.random.RandomState(0)
img = np.array([[1, 1, 1, 0, 0],
[1, 1, 0, 0, 0]], np.float)
result_non_spaced = np.array([[0, 0, 0, 1, 1],
[0, 0, 1, 1, 1]], np.int)
result_spaced = np.array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1]], np.int)
img += 0.1 * rnd.normal(size=img.shape)
seg_non_spaced = slic(img, n_segments=2, sigma=0, multichannel=False,
compactness=1.0)
seg_spaced = slic(img, n_segments=2, sigma=0, spacing=[1, 500, 1],
compactness=1.0, multichannel=False)
assert_equal(seg_non_spaced, result_non_spaced)
assert_equal(seg_spaced, result_spaced)
示例4: slic_data
def slic_data():
for i in range(uu_num_train+uu_num_test):
print "data %d" %(i+1)
img_name = ''
if i < 10:
img_name = '0' + str(i)
else:
img_name = str(i)
#Read first 70 images as floats
img = img_as_float(io.imread('..\data\\training\image_2\uu_0000' + img_name + '.png'))
img_hsv = color.rgb2hsv(img)
gt_img = img_as_float(io.imread('..\data\\training\gt_image_2\uu_road_0000' + img_name + '.png'))
#Create superpixels for training images
image_segment = slic(img, n_segments = numSegments, sigma = 5)
t, train_indices = np.unique(image_segment, return_index=True)
images_train_indices.append(train_indices)
image = np.reshape(img,(1,(img.shape[0]*img.shape[1]),3))
image_hsv = np.reshape(img_hsv,(1,(img_hsv.shape[0]*img_hsv.shape[1]),3))
#images_train.append([image[0][i] for i in train_indices])
images_train_hsv.append([image_hsv[0][i] for i in train_indices])
#Create gt training image values index at train_indices and converted to 1 or 0
gt_image = np.reshape(gt_img, (1,(gt_img.shape[0]*gt_img.shape[1]),3))
gt_image = [1 if gt_image[0][i][2] > 0 else 0 for i in train_indices]
gt_images_train.append(gt_image)
示例5: updateParametros
def updateParametros(val):
global p_segmentos, p_sigma, p_compactness, segments, image, cuda_python
if(val == "Python SLIC"):
cuda_python = 0
elif(val == "CUDA gSLICr"):
cuda_python = 1
p_segmentos = int("%d" % (slider_segmentos.val))
p_sigma = slider_sigma.val
p_compactness = slider_compactness.val
image = c_image.copy()
if(cuda_python == 0):
start_time = time.time()
segments = slic(img_as_float(image), n_segments=p_segmentos, sigma=p_sigma, compactness=p_compactness)
print("--- Tempo Python skikit-image SLIC: %s segundos ---" % (time.time() - start_time))
else:
start_time = time.time()
gSLICrInterface.process( p_segmentos)
print("--- Tempo C++/CUDA gSLICr: %s segundos ---" % (time.time() - start_time))
segments = cuda_seg
obj.set_data(mark_boundaries(img_as_float(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)), segments, outline_color=p_outline))
draw()
示例6: color_histogram
def color_histogram(image_roi, attrs={}, debug=False):
# segment image using kmeans clustering
#segments = slic(image_roi[...,:3], sigma=1, n_segments=10, max_iter=30)
segments = slic(image_roi[...,:3], sigma=1, n_segments=100, max_iter=10)
nsegments = segments.max()
CLASS_COLORS = np.array([ c[1] for c in RGB_COLOR_CLASSES ])/255.
totals = [ 0. for c in RGB_COLOR_CLASSES ]
lesion_mask = image_roi[...,3]
for i in range(nsegments+1):
area = np.logical_and(segments == i, lesion_mask)
segment_size = area.sum()
if segment_size == 0: continue
rgb_average = image_roi[area,:3].mean(axis=0)
delta = CLASS_COLORS - rgb_average
distances = np.sqrt((delta * delta).sum(axis=1))
closest = np.argmin(distances)
totals[closest] += segment_size
totals = np.array(totals) / sum(totals)
for i, v in enumerate(totals):
name = RGB_COLOR_CLASSES[i][0]
attrs["Color Histogram %s" % name] = v
示例7: update_slic
def update_slic(self):
sec = self.auto_submasks_gscene.active_section
t = time.time()
self.slic_labelmaps[sec] = slic(self.contrast_stretched_images[sec].astype(np.float),
sigma=SLIC_SIGMA, compactness=SLIC_COMPACTNESS,
n_segments=SLIC_N_SEGMENTS, multichannel=False, max_iter=SLIC_MAXITER)
sys.stderr.write('SLIC: %.2f seconds.\n' % (time.time() - t)) # 10 seconds, iter=100, nseg=1000;
self.slic_boundary_images[sec] = img_as_ubyte(mark_boundaries(self.contrast_stretched_images[sec],
label_img=self.slic_labelmaps[sec],
background_label=-1, color=(1,0,0)))
self.slic_image_feeder.set_image(sec=sec, numpy_image=self.slic_boundary_images[sec])
self.gscene_slic.update_image(sec=sec)
####
# self.ncut_labelmaps[sec] = normalized_cut_superpixels(self.contrast_stretched_images[sec], self.slic_labelmaps[sec])
self.ncut_labelmaps[sec] = self.slic_labelmaps[sec]
self.sp_dissim_maps[sec] = compute_sp_dissims_to_border(self.contrast_stretched_images[sec], self.ncut_labelmaps[sec])
# self.sp_dissim_maps[sec] = compute_sp_dissims_to_border(self.thresholded_images[sec], self.ncut_labelmaps[sec])
# self.border_dissim_images[sec] = generate_dissim_viz(self.sp_dissim_maps[sec], self.ncut_labelmaps[sec])
# self.dissim_image_feeder.set_image(sec=sec, numpy_image=self.border_dissim_images[sec])
# self.gscene_dissimmap.update_image(sec=sec)
self.selected_dissim_thresholds[sec] = determine_dissim_threshold(self.sp_dissim_maps[sec], self.ncut_labelmaps[sec])
self.ui.slider_dissimThresh.setValue(int(self.selected_dissim_thresholds[sec]/0.01))
######################################################
self.update_init_submasks_image()
示例8: SLIC
def SLIC( Input_Image,ratio, n_segments, sigma):
'''
Description: Segments image using k-means clustering in Color space.
source: skimage, openCv python
parameters: Input_Image : ndarray
Input image, which can be 2D or 3D, and grayscale or multi-channel (see multichannel parameter).
n_segments : int
The (approximate) number of labels in the segmented output image.
ratio: float
Balances color-space proximity and image-space proximity. Higher values give more weight to color-space and yields more square regions
sigma : float
Width of Gaussian smoothing kernel for preprocessing. Zero means no smoothing.
return: Output_mask : ndarray
Integer mask indicating segment labels.
'''
if ratio == 0:
ratio = 0.5
if n_segments == 0:
n_segments = 3
if sigma ==0:
sigma = 1
img = cv2.imread(Input_Image)
segments_slic = slic(img, ratio=0.5, n_segments=3, sigma=1)
print("Slic number of segments: %d" % len(np.unique(segments_slic)))
return segments_slic
示例9: get_segmentation
def get_segmentation(img):
segmentation = slic(img, n_segments=140, compactness=13, sigma=4, enforce_connectivity=True)
# segmentation_img = mark_boundaries(img, segmentation)
# io.imsave('slic.jpg', segmentation_img)
return segmentation
示例10: fun_compare_colorsegmentation_and_display
def fun_compare_colorsegmentation_and_display(image_data, number_segments=250, compactness_factor=10):
"""
The function is a copy of what does this link http://scikit-image.org/docs/dev/auto_examples/plot_segmentations.html
"""
segments_fz = felzenszwalb(image_data, scale=100, sigma=0.5, min_size=50)
segments_slic = slic(image_data, n_segments=number_segments, compactness=compactness_factor, sigma=1)
segments_quick = quickshift(image_data, kernel_size=3, max_dist=6, ratio=0.5)
print ("Felzenszwalb's number of segments: %d" % len(np.unique(segments_fz)))
print ("Slic number of segments: %d" % len(np.unique(segments_slic)))
print ("Quickshift number of segments: %d" % len(np.unique(segments_quick)))
fig, ax = plt.subplots(1, 3, sharex=True, sharey=True, subplot_kw={"adjustable": "box-forced"})
fig.set_size_inches(8, 3, forward=True)
fig.subplots_adjust(0.05, 0.05, 0.95, 0.95, 0.05, 0.05)
ax[0].imshow(mark_boundaries(image_data, segments_fz, color=(1, 0, 0)))
ax[0].set_title("Felzenszwalbs's method")
ax[1].imshow(mark_boundaries(image_data, segments_slic, color=(1, 0, 0)))
ax[1].set_title("SLIC")
ax[2].imshow(mark_boundaries(image_data, segments_quick, color=(1, 0, 0)))
ax[2].set_title("Quickshift")
for a in ax:
a.set_xticks(())
a.set_yticks(())
plt.show()
示例11: getSlic
def getSlic(self):
self.slic = slic(self.depth_image,
n_segments=50,
compactness=.001,
sigma=1,
multichannel=False)
return self.slic
示例12: SuperPixel
def SuperPixel(self, Image):
segments = slic(Image, n_segments=20, sigma=5)
# show the output of SLIC
segments = segments + 1
# So that no labelled region is 0 and ignored by regionprops
label_rgb = color.label2rgb(segments, Image, kind='avg')
return label_rgb
示例13: superpixels
def superpixels(image):
""" given an input image, create super pixels on it
"""
# we could try to limit the problem of holes in boundary by first over segmenting the image
import matplotlib.pyplot as plt
from skimage.segmentation import felzenszwalb, slic, quickshift
from skimage.segmentation import mark_boundaries
from skimage.util import img_as_float
jac_float = img_as_float(image)
plt.imshow(jac_float)
#segments_fz = felzenszwalb(jac_float, scale=100, sigma=0.5, min_size=50)
segments_slic = slic(jac_float, n_segments=600, compactness=0.01, sigma=0.001
#, multichannel = False
, max_iter=50)
fig, ax = plt.subplots(1, 1, sharex=True, sharey=True, subplot_kw={'adjustable':'box-forced'})
fig.set_size_inches(8, 3, forward=True)
fig.subplots_adjust(0.05, 0.05, 0.95, 0.95, 0.05, 0.05)
#ax[0].imshow(mark_boundaries(jac, segments_fz))
#ax[0].set_title("Felzenszwalbs's method")
ax.imshow(mark_boundaries(jac_float, segments_slic))
ax.set_title("SLIC")
return segments_slic
示例14: build_region
def build_region(self):
start_time = time.time();
labels = segmentation.slic(self.q_frame,self.num_superpixels, self.compactness,convert2lab=True,multichannel=True)
_num_superpixels = np.max(labels) + 1;
self.s_frame = color.label2rgb(labels,self.q_frame, kind='avg')
self.freq = np.array([np.sum(labels==label) for label in range(_num_superpixels)])
self.mean = np.array([region['centroid'] for region in regionprops(labels+1)],dtype=np.int16);
self.color_data = np.array([np.sum(self.q_frame[np.where(labels==label)],0) for label in range(_num_superpixels)])
_inv_freq = 1/(self.freq+0.0000001); self.color_data = self.color_data*_inv_freq[:,None]
gray_frame = cv2.cvtColor(self.q_frame,cv2.COLOR_RGB2GRAY)
def texture_prop(label,patch_size = 5):
_mean_min = self.mean[label]-patch_size;
_mean_max = self.mean[label]+patch_size;
glcm = greycomatrix(gray_frame[_mean_min[0]:_mean_max[0],_mean_min[1]:_mean_max[1]],
[3], [0], 256, symmetric=True, normed=True)
_dis = greycoprops(glcm, 'dissimilarity')[0, 0];
_cor = greycoprops(glcm, 'correlation')[0, 0];
return (_dis,_cor);
self.texture_data = np.array([texture_prop(label) for label in range(_num_superpixels)])
self.data = np.hstack((self.color_data,self.texture_data))
cv2.imwrite('outs.png',self.s_frame);
print "Build region (preprocess) : ",time.time()-start_time
return (labels,_num_superpixels);
示例15: remove_background
def remove_background(self):
L_b = 3
self.i_original = self.i_original[self.sub[1]:self.sub[3],self.sub[0]:self.sub[2],]
segments = slic(self.i_original, n_segments=2, compactness=0.1,enforce_connectivity=False)
# segments += 1
temp = self.i_original
if sum(sum(segments[:5,:5])) > 10:
for ii in range(0,3):
temp[:,:,ii] = (np.ones([self.i_original.shape[0],self.i_original.shape[1]])-segments)*self.i_original[:,:,ii]
#Haut, Bas, Droite, Gauche
temp[:L_b,:,ii] = 0
temp[self.i_original.shape[0]-L_b-1:self.i_original.shape[0]-1,:,ii]=0
temp[:,self.i_original.shape[1]-L_b-1:self.i_original.shape[1]-1,ii] = 0
temp[:,:L_b,ii] = 0
else:
for ii in range(0,3):
temp[:,:,ii] = segments*self.i_original[:,:,ii]
# print "else"
#Haut, Bas, Droite, Gauche
temp[:L_b,:,ii] = 0
temp[self.i_original.shape[0]-L_b-1:self.i_original.shape[0]-1,:,ii]=0
temp[:,self.i_original.shape[1]-L_b-1:self.i_original.shape[1]-1,ii] = 0
temp[:,:L_b,ii] = 0
# pdb.set_trace()
fig, ax = plt.subplots(1, 1)
ax.imshow(mark_boundaries(self.i_original,segments))
ax.imshow(temp)
plt.show()
p2, p98 = np.percentile(temp, (2, 98))
temp = exposure.rescale_intensity(temp, in_range=(p2, p98))
return temp