本文整理汇总了Python中skimage.segmentation.mark_boundaries函数的典型用法代码示例。如果您正苦于以下问题:Python mark_boundaries函数的具体用法?Python mark_boundaries怎么用?Python mark_boundaries使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了mark_boundaries函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: 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()
示例2: human_afterloop
def human_afterloop(output_directory, pre_time, fle_name, buffer_directory):
start2 = time()
d_c = import_edited(buffer_directory)
rebw = load(open(buffer_directory+'-'+'DO_NOT_TOUCH_ME.dmp','rb'))
seg_dc = (label(d_c,neighbors=4)+1)*d_c
if np.max(seg_dc)<4:
return 'FAILED: mask for %s looks unsegmented' % fle_name
colormap = repaint_culsters(int(np.max(seg_dc)))
segs = len(set(seg_dc.flatten().tolist()))-1
# shows the result before saving the clustering and printing to the user the number of the images
plt.subplot(1,2,1)
plt.title(fle_name)
plt.imshow(rebw, cmap='gray', interpolation='nearest')
plt.subplot(1,2,2)
plt.title('Segmentation - clusters: %s'%str(segs))
plt.imshow(mark_boundaries(rebw, d_c))
plt.imshow(seg_dc, cmap=colormap, interpolation='nearest', alpha=0.3)
plt.show()
plt.imshow(mark_boundaries(rebw, d_c))
plt.imshow(seg_dc, cmap=colormap, interpolation='nearest', alpha=0.3)
plt.savefig(path.join(output_directory, fle_name+'_%s_clusters.png'%str(segs)), dpi=500, bbox_inches='tight', pad_inches=0.0)
return fle_name+'\t clusters: %s,\t total time : %s'%(segs, "{0:.2f}".format(time()-start2+pre_time))
示例3: test_mark_boundaries
def test_mark_boundaries():
image = np.zeros((10, 10))
label_image = np.zeros((10, 10))
label_image[2:7, 2:7] = 1
ref = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
result = mark_boundaries(image, label_image, color=(1, 1, 1)).mean(axis=2)
assert_array_equal(result, ref)
ref = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 2, 0],
[0, 0, 1, 2, 2, 2, 2, 1, 2, 0],
[0, 0, 1, 2, 0, 0, 0, 1, 2, 0],
[0, 0, 1, 2, 0, 0, 0, 1, 2, 0],
[0, 0, 1, 2, 0, 0, 0, 1, 2, 0],
[0, 0, 1, 1, 1, 1, 1, 2, 2, 0],
[0, 0, 2, 2, 2, 2, 2, 2, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
result = mark_boundaries(image, label_image, color=(1, 1, 1),
outline_color=(2, 2, 2)).mean(axis=2)
assert_array_equal(result, ref)
示例4: test_mark_boundaries
def test_mark_boundaries():
image = np.zeros((10, 10))
label_image = np.zeros((10, 10), dtype=np.uint8)
label_image[2:7, 2:7] = 1
ref = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 0, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 0, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 0, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
marked = mark_boundaries(image, label_image, color=white, mode='thick')
result = np.mean(marked, axis=-1)
assert_array_equal(result, ref)
ref = np.array([[0, 2, 2, 2, 2, 2, 2, 2, 0, 0],
[2, 2, 1, 1, 1, 1, 1, 2, 2, 0],
[2, 1, 1, 1, 1, 1, 1, 1, 2, 0],
[2, 1, 1, 2, 2, 2, 1, 1, 2, 0],
[2, 1, 1, 2, 0, 2, 1, 1, 2, 0],
[2, 1, 1, 2, 2, 2, 1, 1, 2, 0],
[2, 1, 1, 1, 1, 1, 1, 1, 2, 0],
[2, 2, 1, 1, 1, 1, 1, 2, 2, 0],
[0, 2, 2, 2, 2, 2, 2, 2, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
marked = mark_boundaries(image, label_image, color=white,
outline_color=(2, 2, 2), mode='thick')
result = np.mean(marked, axis=-1)
assert_array_equal(result, ref)
示例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: overlay_cells
def overlay_cells(cells, image, colors):
"Overlay the edges of each individual cell in the provided image"
tmp = color.gray2rgb(image)
for k in cells.keys():
c = cells[k]
if c.selection_state == 1:
col = colors[c.color_i][:3]
for px in c.outline:
x, y = px
tmp[x, y] = col
if c.sept_mask is not None:
try:
x0, y0, x1, y1 = c.box
tmp[x0:x1, y0:y1] = mark_boundaries(tmp[x0:x1, y0:y1],
img_as_int(
c.sept_mask),
color=col)
except IndexError:
c.selection_state = -1
return tmp
示例7: grabcut
def grabcut(img, targetness):
u"""
Segmenting the best target-like region from an targetness map.
"""
mask = np.ones(img.shape[:2], np.uint8) * cv2.GC_BGD
score_th = scoreatpercentile(targetness, 95)
mask[targetness >= score_th] = cv2.GC_PR_FGD
score_th = scoreatpercentile(targetness, 99)
mask[targetness >= score_th] = cv2.GC_FGD
mask = cv2.medianBlur(mask, 15)
bgdModel = np.zeros((1, 65), np.float64)
fgdModel = np.zeros((1, 65), np.float64)
cv2.grabCut(img, mask, None, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_MASK)
mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
lab_mask2 = bwlabel(mask2)
lab_list = np.unique(lab_mask2.flatten())[1:]
lab_argmax = np.argmax(
[np.max(targetness[lab_mask2 == i]) for i in lab_list])
mask2[lab_mask2 != lab_list[lab_argmax]] = 0
img2 = img.copy()
img2[mask2 < 1, :] = [0, 43, 54]
img2 = mark_boundaries(img2, mask2)
return img2, mask2
示例8: 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()
示例9: intensity_range2superpixels
def intensity_range2superpixels(im, superpixels, intMinT=0.95, intMaxT=1.05, debug=False, intMin=0, intMax=255):#, fromInt=0, toInt=255):
superseeds = np.zeros_like(superpixels)
#if not intMin and not intMax:
# hist, bins = skexp.histogram(im)
#
# #zeroing values that are lower/higher than fromInt/toInt
# toLow = np.where(bins < fromInt)
# hist[toLow] = 0
# toHigh = np.where(bins > toInt)
# hist[toHigh] = 0
#
# max_peakIdx = hist.argmax()
# intMin = intMinT * bins[max_peakIdx]
# intMax = intMaxT * bins[max_peakIdx]
sp_means = np.zeros(superpixels.max()+1)
for sp in range(superpixels.max()+1):
values = im[np.where(superpixels==sp)]
mean = np.mean(values)
sp_means[sp] = mean
idxs = np.argwhere(np.logical_and(sp_means>=intMin, sp_means<=intMax))
for i in idxs:
superseeds = np.where(superpixels==i[0], 1, superseeds)
if debug:
plt.figure(), plt.gray()
plt.imshow(im), plt.hold(True), plt.imshow(mark_boundaries(im, superseeds, color=(1,0,0)))
plt.axis('image')
plt.show()
return superseeds
示例10: createFigure4
def createFigure4(list_file, list_param, corpus_meta, prob_topic_doc, segment_dir, n_topic, output_dir):
for file_item in list_file:
print file_item
for topic in range(n_topic):
print topic
fig = plt.figure()
img = img_as_float(io.imread(img_dir+file_item+'.ppm'))
ax1 = fig.add_subplot(4,4, 1, axisbg='grey')
ax1.set_xticks(()), ax1.set_yticks(())
ax1.imshow(img)
index=2
for param in list_param:
if 'slic' in param:
# print 'test', index
# print corpus_meta[0][1].split('-')[0]
segment_in_file = [item_corpus for item_corpus in corpus_meta if file_item == item_corpus[1].split('-')[0]]
print len(segment_in_file)
segments_res = csv2Array(segment_dir+'/'+file_item+'/'+file_item+'-'+param+'.sup')
img = img_as_float(io.imread(img_dir+file_item+'.ppm'))
output = np.zeros( (len(img), len(img[0])) )
for segment in segment_in_file:
# print prob_topic_doc[int(segment[0])][topic]
output[segments_res == int(segment[2])] = prob_topic_doc[int(segment[0])][topic]
output = mark_boundaries(output, segments_res)
ax1 = fig.add_subplot(4,4, index, axisbg='grey')
# ax1 = fig.add_subplot(5,10, index, axisbg='grey')
ax1.set_xticks(()), ax1.set_yticks(())
ax1.imshow(output)
index += 1
ensure_path(output_dir+'/'+file_item+'/')
plt.savefig(output_dir+'/'+file_item+'/topic-'+str(topic)+'-'+file_item+'.pdf')
plt.clf()
plt.close()
示例11: 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
示例12: plot
def plot(self):
self.ax.cla()
if self.segment_label is None:
self.ax.imshow(self.new_image)
else:
boundary_image = segmentation.mark_boundaries(self.new_image, self.segment_label)
self.ax.imshow(boundary_image)
self.ax.imshow(self.background_mask.astype(float), alpha=0.3)
mask = 1 - self.background_mask
content_on_canvas = np.zeros(list(mask.shape) + [4], np.uint8) # Prepare the canvas
for stitch_image in self.stitch_images:
content = stitch_image['content']
x = stitch_image['x']
y = stitch_image['y']
size = stitch_image['size']
print(x, y, size)
resized = misc.imresize(content, size) # Resize the image
# Compute the intersecting length between canvas and content
x_copy_width = mask.shape[1] - stitch_image['x']
if resized.shape[1] < x_copy_width:
x_copy_width = resized.shape[1]
y_copy_width = mask.shape[0] - stitch_image['y']
if resized.shape[0] < y_copy_width:
y_copy_width = resized.shape[0]
print(x_copy_width, y_copy_width)
# Copy content onto canvas and apply mask
new_content = np.zeros(list(mask.shape) + [4], np.uint8)
new_content[y:y+y_copy_width, x:x+x_copy_width, :] = resized[0:y_copy_width, 0:x_copy_width, :]
content_on_canvas = self.merge(content_on_canvas, new_content)
content_on_canvas[:, :, 3] = np.multiply(mask, content_on_canvas[:, :, 3])
self.ax.imshow(content_on_canvas)
self.ax.figure.canvas.draw()
示例13: generateImageWithSuperPixelBoundaries
def generateImageWithSuperPixelBoundaries(image, segmentationMask):
# Function returns an image with superpixel boundaries displayed as lines. It is assumed that the image was the source for the segmentation mask.
# See [http://scikit-image.org/docs/dev/api/skimage.segmentation.html?highlight=slic#skimage.segmentation.mark_boundaries]
# Function signature: skimage.segmentation.mark_boundaries(image, label_img, color=(1, 1, 0), outline_color=(0, 0, 0))
superPixelImage = mark_boundaries(image, segmentationMask)
return superPixelImage
示例14: explain
def explain(model, img, topLabels, numSamples, numFeatures, hideRest, hideColor, positiveOnly):
img, oldImg = transform_img_fn(img)
img = img*(1./255)
prediction = model.predict(img)
explainer = lime_image.LimeImageExplainer()
img = np.squeeze(img)
explanation = explainer.explain_instance(img, model.predict, top_labels=topLabels, hide_color=hideColor, num_samples=numSamples)
temp, mask = explanation.get_image_and_mask(getTopPrediction(prediction[0]), positive_only=positiveOnly, num_features=numFeatures, hide_rest=hideRest)
tempMask = mask * 255
temp = Image.fromarray(np.uint8(tempMask))
temp = temp.resize((oldImg.width, oldImg.height))
temp = image.img_to_array(temp)
temp = temp * 1./255
temp = temp.astype(np.int64)
temp = np.squeeze(temp)
oldImgArr = image.img_to_array(oldImg)
oldImgArr = oldImgArr * (1./255)
oldImgArr = oldImgArr.astype(np.float64)
imgExplained = mark_boundaries(oldImgArr, temp)
imgFinal = np.uint8(imgExplained*255)
img = Image.fromarray(imgFinal)
imgByteArr = io.BytesIO()
img.save(imgByteArr, format='JPEG')
imgByteArr = imgByteArr.getvalue()
return imgByteArr
示例15: visualize_pascal
def visualize_pascal(plot_probabilities=False):
data = load_pascal('val')
ds = PascalSegmentation()
for x, y, f, sps in zip(data.X, data.Y, data.file_names, data.superpixels):
fig, ax = plt.subplots(2, 3)
ax = ax.ravel()
image = ds.get_image(f)
y_pixel = ds.get_ground_truth(f)
x_raw = load_kraehenbuehl(f)
boundary_image = mark_boundaries(image, sps)
ax[0].imshow(image)
ax[1].imshow(y_pixel, cmap=ds.cmap)
ax[2].imshow(boundary_image)
ax[3].imshow(np.argmax(x_raw, axis=-1), cmap=ds.cmap, vmin=0, vmax=256)
ax[4].imshow(y[sps], cmap=ds.cmap, vmin=0, vmax=256)
ax[5].imshow(np.argmax(x, axis=-1)[sps], cmap=ds.cmap, vmin=0,
vmax=256)
for a in ax:
a.set_xticks(())
a.set_yticks(())
plt.savefig("figures_pascal_val/%s.png" % f, bbox_inches='tight')
plt.close()
if plot_probabilities:
fig, ax = plt.subplots(3, 7)
for k in range(21):
ax.ravel()[k].matshow(x[:, :, k], vmin=0, vmax=1)
for a in ax.ravel():
a.set_xticks(())
a.set_yticks(())
plt.savefig("figures_pascal_val/%s_prob.png" % f,
bbox_inches='tight')
plt.close()
tracer()