本文整理汇总了Python中skimage.segmentation.clear_border函数的典型用法代码示例。如果您正苦于以下问题:Python clear_border函数的具体用法?Python clear_border怎么用?Python clear_border使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了clear_border函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: scikit_example_plot_label
def scikit_example_plot_label():
image = data.coins()[50:-50, 50:-50]
# apply threshold
thresh = threshold_otsu(image)
bw = closing(image > thresh, square(3))
# remove artifacts connected to image border
cleared = bw.copy()
clear_border(cleared)
# label image regions
label_image = label(cleared)
borders = np.logical_xor(bw, cleared)
label_image[borders] = -1
fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))
ax.imshow(label_image, cmap='jet')
for region in regionprops(label_image, ['Area', 'BoundingBox']):
# skip small images
if region['Area'] < 100:
continue
# draw rectangle around segmented coins
minr, minc, maxr, maxc = region['BoundingBox']
rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
fill=False, edgecolor='red', linewidth=2)
ax.add_patch(rect)
plt.show()
示例2: setROILED
def setROILED(self, im):
im1 = im.copy()
box = self.pupil_BOX
x,y,w,h = box + [-20,-30, 40, 60]
self.led_OFFSET = np.array([x,y])
im2 = im[y:y+h, x:x+w]
center_point = [e / 2 for e in im2.shape]
for ledthreshold in xrange(210, 150, -2):
ret, bw_im = cv2.threshold(im2, ledthreshold, 255, cv2.THRESH_BINARY)
cleared = bw_im.copy()
clear_border(cleared)
label_img = label(cleared)
props = regionprops(label_img)
if len(props) < 2:
continue
elif len(props) >= 2:
dist = [euclidean(center_point, e.centroid) for e in props]
minDist_idx = [dist.index(e) for e in heapq.nsmallest(2, dist)]
props[0], props[1] = props[minDist_idx[0]], props[minDist_idx[1]]
if props[0].area > 27 and props[1].area > 27 and props[0].area < 60 and props[1].area < 60:
return bw_im, props[0].centroid, props[1].centroid
return None, None, None
示例3: del_small
def del_small(self,img,min_size):
'''
args : -> 画像,1ch
dst : -> 端に繋がってるのと小さいやつ除去した画像
param: ->
'''
bounding_box = np.zeros_like(img)
# 画像の端に繋がってるやつ削除
cleared = img.copy()
skseg.clear_border(cleared)
# ラベリング
labels, num = sk.label(cleared, return_num = True) # numが一個多い?
# bounding boxの描画
# for region in sk.regionprops(labels):
# minr, minc, maxr, maxc = region.bbox
# if region.area < min_size:
# cleared[minr:maxr,minc:maxc][region.convex_image == True] =0
# num = num - 1
# else:
# cv2.rectangle(bounding_box,(minc,minr),(maxc,maxr),255)
bounding_box = 0
return cleared, num, bounding_box
示例4: applyMorphologicalCleaning
def applyMorphologicalCleaning(self, image):
"""
Applies a variety of morphological operations to improve the detection
of worms in the image.
Takes 0.030 s on MUSSORGSKY for a typical frame region
Takes 0.030 s in MATLAB too
"""
# start with worm == 1
image = image.copy()
segmentation.clear_border(image) # remove objects at edge (worm == 1)
# fix defects in the thresholding by closing with a worm-width disk
# worm == 1
wormSE = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,
(self.wormDiskRadius+1,
self.wormDiskRadius+1))
imcl = cv2.morphologyEx(np.uint8(image), cv2.MORPH_CLOSE, wormSE)
imcl = np.equal(imcl, 1)
# fix defects by filling holes
imholes = ndimage.binary_fill_holes(imcl)
imcl = np.logical_or(imholes, imcl)
# fix barely touching regions
# majority with worm pixels == 1 (median filter same?)
imcl = nf.median_filter(imcl, footprint=[[1, 1, 1],
[1, 0, 1],
[1, 1, 1]])
# diag with worm pixels == 0
imcl = np.logical_not(bwdiagfill(np.logical_not(imcl)))
# open with worm pixels == 1
openSE = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 1))
imcl = cv2.morphologyEx(np.uint8(imcl), cv2.MORPH_OPEN, openSE)
return np.equal(imcl, 1)
示例5: roofRegion
def roofRegion(edge):
"""Estimate region based on edges of roofRegion
"""
# apply threshold
thresh = threshold_otsu(image)
bw = closing(image > thresh, square(3))
# remove artifacts connected to image border
cleared = bw.copy()
clear_border(cleared)
# label image regions
label_image = label(cleared)
borders = np.logical_xor(bw, cleared)
label_image[borders] = -1
image_label_overlay = label2rgb(label_image, image=image)
fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))
ax.imshow(image_label_overlay)
for region in regionprops(label_image):
# skip small images
if region.area < 100:
continue
# draw rectangle around segmented coins
minr, minc, maxr, maxc = region.bbox
rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
fill=False, edgecolor='red', linewidth=2)
ax.add_patch(rect)
plt.show()
示例6: detect_edges
def detect_edges(image_array):
""" Detect edges in a given image
Takes a numpy.array representing an image,
apply filters and edge detection and return a numpy.array
Parameters
----------
image_array : ndarray (2D)
Image data to be processed. Detect edges on this 2D array representing the image
Returns
-------
edges : ndarray (2D)
Edges of an image.
"""
#Transform image into grayscale
img = rgb2gray(image_array)
#Remove some noise from the image
img = denoise_tv_chambolle(img, weight=0.55)
#Apply canny
edges = filter.canny(img, sigma=3.2)
#Clear the borders
clear_border(edges, 15)
#Dilate edges to make them more visible and connected
edges = binary_dilation(edges, selem=diamond(3))
return edges
示例7: test_clear_border_3d
def test_clear_border_3d():
image = np.array([
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[1, 0, 0, 0]],
[[0, 0, 0, 0],
[0, 1, 1, 0],
[0, 0, 1, 0],
[0, 0, 0, 0]],
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]],
])
# test default case
result = clear_border(image.copy())
ref = image.copy()
ref[0, 3, 0] = 0
assert_array_equal(result, ref)
# test buffer
result = clear_border(image.copy(), 1)
assert_array_equal(result, np.zeros(result.shape))
# test background value
result = clear_border(image.copy(), buffer_size=1, bgval=2)
assert_array_equal(result, 2 * np.ones_like(image))
示例8: getRegions
def getRegions():
"""Geocode address and retreive image centered
around lat/long"""
address = request.args.get('address')
results = Geocoder.geocode(address)
lat, lng = results[0].coordinates
zip_code = results[0].postal_code
map_url = 'https://maps.googleapis.com/maps/api/staticmap?center={0},{1}&size=640x640&zoom=19&sensor=false&maptype=roadmap&&style=visibility:simplified|gamma:0.1'
request_url = map_url.format(lat, lng)
req = urllib.urlopen(request_url)
img = io.imread(req.geturl(),flatten=True)
labels, numobjects = ndimage.label(img)
image = filter.canny(img, sigma=3)
thresh = threshold_otsu(image)
bw = closing(image > thresh, square(3))
# remove artifacts connected to image border
cleared = bw.copy()
clear_border(cleared)
# label image regions
label_image = label(cleared)
borders = np.logical_xor(bw, cleared)
label_image[borders] = -1
image_label_overlay = label2rgb(label_image, image=image)
fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))
ax.imshow(image_label_overlay)
示例9: segmentToRegions
def segmentToRegions(image, num_of_ones, bw):
#apply threshold
struct = buildStruct(30, num_of_ones)
if num_of_ones == 0:
img_close = bw
else:
img_close = opening(bw, struct)
# remove artifacts connected to image border
cleared = img_close.copy()
clear_border(cleared)
# label image regions
label_image = label(cleared)
borders = np.logical_xor(img_close, cleared)
label_image[borders] = -1
#image_label_overlay = label2rgb(label_image, image=image)
regions = regionprops(label_image)
"""
fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))
ax.imshow(image_label_overlay)
for region in regions:
# skip small images
if region.area < 10:
continue
# draw rectangle around segmented coins
minr, minc, maxr, maxc = region.bbox
rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
fill=False, edgecolor='blue', linewidth=2)
ax.add_patch(rect)
"""
return regions
示例10: __call__
def __call__(self, image, window_size=10, threshold=0, fill_holes=True,
outline_smoothing=2, remove_borderobjects=True, size_min=1,
*args, **kw):
thresh = threshold_adaptive(image, block_size=window_size,
offset=-1*threshold)
if outline_smoothing >= 1:
thresh = outlineSmoothing(thresh, outline_smoothing)
thresh = remove_small_objects(thresh, size_min)
seeds = ndi.label(clear_border(~thresh))[0]
thresh = ndi.binary_fill_holes(thresh)
smask = seeds.astype(bool)
# object don't touch border after outline smoothing
if remove_borderobjects:
thresh = clear_border(thresh)
img = np.zeros(thresh.shape)
img[~smask] = 1
edt = ndi.morphology.distance_transform_edt(img)
edt -= ndi.morphology.distance_transform_edt(seeds)
labels = watershed(edt, seeds)
labels[smask] = 0
labels[~thresh] = 0
return labels
示例11: get_cells
def get_cells(image):
'''
Get cellls from the polygon.
'''
# apply threshold
thresh = threshold_otsu(image)
binary = image > thresh
bw=binary
plt.imshow(bw)
# Remove connected to image border
cleared = bw.copy()
clear_border(cleared)
# label image regions
label_image = skimage.measure.label(cleared)
#find_contours
borders = np.logical_xor(bw, cleared)
label_image[borders] = -1
image_label_overlay = label2rgb(label_image, image=image)
#extract the regions and get a polygon per region
polygons=[]
for i,region in enumerate(regionprops(label_image)):
# skip small images
if region.area < 100:
continue
a=np.zeros([len(region.coords),2])
#a=np.zeros(
plt.imshow(bw)
for i in range(len(region.coords)):
a[i,:]=[region.coords[i][0],region.coords[i][1]]
polygons.append(a)
return polygons
示例12: get_cells
def get_cells(image):
'''
Get cellls from the polygon.
'''
new_image=np.ones([3,image.shape[0],image.shape[1]],dtype=float)
# apply threshold
thresh = threshold_otsu(image)
bw=image
# remove artifacts connected to image border
cleared = bw.copy()
clear_border(cleared)
# label image regions
label_image = label(cleared)
#skimage.measure.label
#find_contours
borders = np.logical_xor(bw, cleared)
label_image[borders] = -1
image_label_overlay = label2rgb(label_image, image=image)
#extract the regions and get a polygon per region
polygons=[]
for i,region in enumerate(regionprops(label_image)):
# skip small images
if region.area < 100:
continue
#polygons.append(matplotlib.path.Path(region.coords))
print (region.coords.shape)
a=np.zeros(region.coords.shape)
a[:,0]=region.coords[:,1]
a[:,1]=region.coords[:,0]
polygons.append(a)
return polygons
示例13: getArea
def getArea(address):
"""Geocode address and retreive image centered
around lat/long"""
address = address
results = Geocoder.geocode(address)
lat, lng = results[0].coordinates
zip_code = results[0].postal_code
map_url = 'https://maps.googleapis.com/maps/api/staticmap?center={0},{1}&size=640x640&zoom=19&sensor=false&maptype=roadmap&&style=visibility:simplified|gamma:0.1'
request_url = map_url.format(lat, lng)
req = urllib.urlopen(request_url)
img = io.imread(req.geturl(),flatten=True)
labels, numobjects = ndimage.label(img)
image = filter.canny(img, sigma=3)
thresh = threshold_otsu(image)
bw = closing(image > thresh, square(3))
# remove artifacts connected to image border
cleared = bw.copy()
clear_border(cleared)
# label image regions
label_image = label(cleared)
borders = np.logical_xor(bw, cleared)
label_image[borders] = -1
image_label_overlay = label2rgb(label_image, image=image)
fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))
ax.imshow(image_label_overlay)
dist = []
rp = regionprops(label_image)
rp = [x for x in rp if 100 < x.area <= 900]
for region in rp:
# skip small images
#if region.area < 100:
# continue
dist.append(sqrt( ( 320-region.centroid[0] )**2 + ( 320-region.centroid[1] )**2 ))
# draw rectangle around segmented coins
#minr, minc, maxr, maxc = region.bbox
#rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
# fill=False, edgecolor='red', linewidth=2)
#ax.add_patch(rect)
roof_index = dist.index(min(dist))
minr, minc, maxr, maxc = rp[roof_index].bbox
rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
fill=False, edgecolor='red', linewidth=2)
ax.add_patch(rect)
img = StringIO()
fig.savefig(img)
img.seek(0)
session['roof_area'] = rp[roof_index].area
roof_area = (rp[roof_index].area)*12
return(roof_area)
示例14: adaptivethresh_and_hough
def adaptivethresh_and_hough(image):
'''
image = square NDVI image of field
Applies adaptive thresholding and cleaning on NDVI image to prepare for hough line transformation
'''
# apply adaptive opencv threshold
th3 = cv2.adaptiveThreshold(image,255,cv2.ADAPTIVE_THRESH_MEAN_C,\
cv2.THRESH_BINARY,95,2)
# Remove noise bij opening
kernel = np.ones((3,3),np.uint8)
opening = cv2.morphologyEx(th3, cv2.MORPH_OPEN, kernel)
# close image using scikit
#bw = closing(th3 > opening, square(14))
# remove artifacts connected to image border
cleared = opening.copy()
clear_border(cleared)
# label image regions
crop_regions = label(cleared)
# Remove noise by area
region_size = np.bincount(crop_regions.ravel())
region_mask = region_size > 200
region_mask[0] = 0
regions_cleaned = region_mask[crop_regions]
# Convert image to CV image
cv_image = img_as_ubyte(regions_cleaned)
# Apply hough line transformation
lines = cv2.HoughLinesP(cv_image,rho=1,theta=np.pi/180,threshold=200,lines=np.array([]),
minLineLength=100,maxLineGap=5) # TO DO: MAKE SURE ONLY 180 RANGE IS RETURNED and minlinelength automatic adjust
if not lines.any():
print "Error: No Hough lines detected! Try to increase cropping area" # <- line not working, as lines is more than 1!
sys.exit()
else:
for line in lines:
x1,y1,x2,y2 = line[0]
cv2.line(cv_image,(x1,y1),(x2,y2),(50,255,10),2)
# Extract only the coordinates from NP array
coordinates = lines[0:,0,]
np.save('coordinates.npy', coordinates)
np.savetxt('coordinates.txt', coordinates)
cv2.imwrite('detected_lines.png', cv_image)
return coordinates
示例15: parse_image
def parse_image(self):
self.m_print("Parsing panel image",0)
thresh = threshold_otsu(self.i_file)
bw = closing(self.i_file > thresh, square(3))
# remove artifacts connected to image border
cleared = bw.copy()
clear_border(cleared)
# label image regions
label_image = label(cleared)
borders = np.logical_xor(bw, cleared)
label_image[borders] = -1
return label2rgb(label_image, image=self.i_file),label_image