本文整理汇总了Python中skimage.morphology.opening函数的典型用法代码示例。如果您正苦于以下问题:Python opening函数的具体用法?Python opening怎么用?Python opening使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了opening函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ApplyThresholdToImageRegion
def ApplyThresholdToImageRegion(image2, Tb, Bb, Lb, Rb,shouldThresholdImage):
image = rgb2gray(image2)
global foregroundPixelValue
global backgroundPixelValue
thresholdValue = threshold_otsu(image)
NumberOfRows = image.shape[0]
NumberOfColumns = image.shape[1]
numberOfBlackPixels = 0
numberOfWhitePixels = 0
selem = disk(3)
# simpe thresholding
for y in range(NumberOfRows):
for x in range(NumberOfColumns):
isWithinBoundary = IsWithinBoundary(y,x,image2, Tb, Bb, Lb, Rb,shouldThresholdImage)
if (isWithinBoundary):
if image[y,x] > thresholdValue:
#black
image[y,x] = 0
numberOfBlackPixels += 1
else:
#white
image[y,x] = 1
numberOfWhitePixels += 1
# assume foreground has more pixels in face region
if (numberOfWhitePixels > numberOfBlackPixels):
foregroundPixelValue = 1
backgroundPixelValue = 0
#print("foreground color is white")
else:
foregroundPixelValue = 0
backgroundPixelValue = 1
#print("foreground color is black")
image = opening(image,selem)
if (foregroundPixelValue == 0):
image = opening(image,selem)
else:
image = closing(image,selem)
if drawFaceImages:
io.imshow(image)
io.show()
return image
示例2: upsample_smooth
def upsample_smooth(image):
filename_split = os.path.splitext(image)
filename_zero, fileext = filename_split
basename = os.path.basename(filename_zero)
upsampleRes = int(upsampleRes)
upsampled_image = outPath+basename+'_cubicSpline.png'
os.system("gdalwarp -tr", upsample_res, upsample_res," -r cubicspline ", image, upsampled_image)
im = np.array(Image.open(upsampled_image))
with rasterio.open(image) as r:
im = r.read()
p = r.profile
im = im.squeeze()
selem = disk(1)
print("image min and max: ", im.min(),im.max())
dilated = skimage.morphology.dilation(im, selem)
print("dilated image min and max: ", dilated.min(),dilated.max())
eroded = skimage.morphology.erosion(im, selem)
print("eroded image min and max: ", eroded.min(),eroded.max())
opened = opening(im, selem)
print("opened image min and max: ", opened.min(),opened.max())
closed = closing(im, selem)
print("closed image min and max: ", closed.min(),closed.max())
dilated = Image.fromarray(dilated)
dilated.save(outPath+basename+'.png')
with rasterio.open(outPath+basename+fileext, 'w', **p) as dst:
dst.write(dilated, 1)
color_outPath = outPath+'color/'
if not os.path.exists(color_outPath):
os.mkdir(color_outPath)
colored_image = color_outPath+basename+'.png'
os.system("gdaldem color-relief", dilated, colorfile, colored_image)
return im, dilated, eroded, opened, closed
示例3: Mask_ROI_op
def Mask_ROI_op(im,disk_size,thresh=None,black_spots=None,with_morph=False):
l=np.array([0,0])
if not isinstance(im,l.__class__):
numpy_array=np.array(im)
else:
numpy_array=im
if len(numpy_array.shape)==3:
numpy_array=numpy_array[:,:,0:3].mean(axis=2)
selem = disk(disk_size)
openin = opening(numpy_array, selem)
if thresh is None:
thresh = threshold_otsu(openin)
binary = openin > thresh
if binary.dtype=='bool':
binary=binary+0
if black_spots is not None:
binary2 = openin > black_spots
binary2 = binary2 + 0
binary = binary - binary2
else:
binary -=1
binary=binary * -1
if with_morph:
return(binary,openin)
else:
return(binary)
示例4: open_image
def open_image(img, mask_length):
# Morphological opening on greyscale/binary image
img = img.astype(np.uint8)
img = opening(img, rectangle(mask_length,1))
return(img)
示例5: detectOpticDisc
def detectOpticDisc(image):
kernel = octagon(10, 10)
thresh = threshold_otsu(image[:,:,1])
binary = image > thresh
print binary.dtype
luminance = convertToHLS(image)[:,:,2]
t = threshold_otsu(luminance)
t = erosion(luminance, kernel)
labels = segmentation.slic(image[:,:,1], n_segments = 3)
out = color.label2rgb(labels, image[:,:,1], kind='avg')
skio.imshow(out)
x, y = computeCentroid(t)
print x, y
rows, cols, _ = image.shape
p1 = closing(image[:,:,1],kernel)
p2 = opening(p1, kernel)
p3 = reconstruction(p2, p1, 'dilation')
p3 = p3.astype(np.uint8)
#g = dilation(p3, kernel)-erosion(p3, kernel)
#g = rank.gradient(p3, disk(5))
g = cv2.morphologyEx(p3, cv2.MORPH_GRADIENT, kernel)
#markers = rank.gradient(p3, disk(5)) < 10
markers = drawCircle(rows, cols, x, y, 85)
#markers = ndimage.label(markers)[0]
#skio.imshow(markers)
g = g.astype(np.uint8)
#g = cv2.cvtColor(g, cv2.COLOR_GRAY2RGB)
w = watershed(g, markers)
print np.max(w), np.min(w)
w = w.astype(np.uint8)
#skio.imshow(w)
return w
示例6: smooth
def smooth(image):
filename_split = os.path.splitext(image)
filename_zero, fileext = filename_split
basename = os.path.basename(filename_zero)
im = np.array(Image.open(image))
with rasterio.open(image) as r:
im = r.read()
p = r.profile
im = im.squeeze()
selem = disk(1)
print("image min and max: ", im.min(),im.max())
dilated = skimage.morphology.dilation(im, selem)
print("dilated image min and max: ", dilated.min(),dilated.max())
eroded = skimage.morphology.erosion(im, selem)
print("eroded image min and max: ", eroded.min(),eroded.max())
opened = opening(im, selem)
print("opened image min and max: ", opened.min(),opened.max())
closed = closing(im, selem)
print("closed image min and max: ", closed.min(),closed.max())
#im[im==1]=0
#im[im==2]=1
median = cv2.medianBlur(im,9)
average = cv2.blur(im,(9,9))
#gaussian = cv2.GaussianBlur(im,(9,9),0)
gaussian = cv2.GaussianBlur(dilated,(9,9),0)
#bilateral = cv2.bilateralFilter(im,9,75,75)
bilateral = cv2.bilateralFilter(gaussian,9,75,75)
with rasterio.open(outPath+basename+fileext, 'w', **p) as dst:
dst.write(bilateral, 1)
color_outPath = outPath+'color/'
if not os.path.exists(color_outPath):
os.mkdir(color_outPath)
colored_image = color_outPath+basename+'.png'
os.system("gdaldem color-relief", bilateral, colorfile, colored_image)
return im, dilated, eroded, opened, closed, median, average, gaussian, bilateral
示例7: opening
def opening(gray_img, kernel=None):
"""Wrapper for scikit-image opening functions. Opening can remove small bright spots (i.e. salt).
Inputs:
gray_img = input image (grayscale or binary)
kernel = optional neighborhood, expressed as an array of 1s and 0s. If None, use cross-shaped structuring element.
:param gray_img: ndarray
:param kernel = ndarray
:return filtered_img: ndarray
"""
params.device += 1
# Make sure the image is binary/grayscale
if len(np.shape(gray_img)) != 2:
fatal_error("Input image must be grayscale or binary")
# If image is binary use the faster method
if len(np.unique(gray_img)) == 2:
bool_img = morphology.binary_opening(gray_img, kernel)
filtered_img = np.copy(bool_img.astype(np.uint8) * 255)
# Otherwise use method appropriate for grayscale images
else:
filtered_img = morphology.opening(gray_img, kernel)
if params.debug == 'print':
print_image(filtered_img, os.path.join(params.debug_outdir, str(params.device) + '_opening' + '.png'))
elif params.debug == 'plot':
plot_image(filtered_img, cmap='gray')
return filtered_img
示例8: get_nuclei
def get_nuclei(img, opening_radius=6, block_size=80, threshold_offset=0):
s = Sample(DOWNSAMPLE)
binary = threshold_adaptive(s.downsample(img), int(block_size / s.rate), offset=threshold_offset)
filled = fill_holes(binary)
opened = opening(filled, selem=disk(opening_radius / s.rate))
nuclei = apply_watershed(opened)
nuclei = s.upsample(nuclei)
return img_as_uint(nuclei)
示例9: segment_image
def segment_image(image, plantid, threshold, locations, opening_size=5):
"""
Segments an image based on simple thresholding
Inputs:
- image : the image (as a numpy array)
- plantid : which plant on the image (int)
- threshold : the threshold to use
- locations : the coordinates of the plants in the
Output:
- mask of the image
"""
image_part = get_piece(image, locations[plantid])
mask = median_filter(image_part.mean(2), (4,4)) > threshold
opening(mask, selem=square(opening_size), out=mask) # open image, remove
# clutter
return mask # gaussian_filter(image_part[mask, :], sigma=convolve_sigma)
示例10: func
def func(frame):
_dtype = frame.dtype
kernel = mor.disk(3)
frameWP = frame - mor.white_tophat(frame, kernel) * (mor.white_tophat(frame, kernel) > 1000).astype(float)
kernel = mor.rectangle(25, 1)
closed = mor.closing(frameWP, kernel)
opened = mor.opening(closed, kernel)
result = ((frameWP.astype(float) / opened.astype(float)) * 3000.0)
return result.astype(_dtype)
示例11: ProcessImage
def ProcessImage(im, targetDim = 250, doDenoiseOpening = True):
#Resize to specified pixels max edge size
scaling = 1.
if im.shape[0] > im.shape[1]:
if im.shape[0] != targetDim:
scaling = float(targetDim) / im.shape[0]
im = misc.imresize(im, (targetDim, int(round(im.shape[1] * scaling))))
else:
if im.shape[1] != targetDim:
scaling = float(targetDim) / im.shape[1]
im = misc.imresize(im, (int(round(im.shape[0] * scaling)), targetDim))
#print "scaling", scaling
greyim = 0.2126 * im[:,:,0] + 0.7152 * im[:,:,1] + 0.0722 * im[:,:,2]
#Highlight number plate
imnorm = np.array(greyim, dtype=np.uint8)
se = np.ones((3, 30), dtype=np.uint8)
opim = morph.opening(imnorm, se)
diff = greyim - opim + 128.
misc.imsave("diff.png", diff)
#Binarize image
vals = diff.copy()
vals = vals.reshape((vals.size))
meanVal = vals.mean()
stdVal = vals.std()
threshold = meanVal + stdVal
#print "Threshold", threshold
binIm = diff > threshold
misc.imsave("threshold.png", binIm)
#print vals.shape
#plt.plot(vals)
#plt.show()
#Denoise
diamond = morph.diamond(2)
if doDenoiseOpening:
currentIm = morph.binary_opening(binIm, diamond)
else:
currentIm = binIm
denoiseIm2 = morph.binary_closing(currentIm, np.ones((3, 13)))
#print "currentIm", currentIm.min(), currentIm.max(), currentIm.mean()
#print "denoiseIm2", denoiseIm2.min(), denoiseIm2.max(), currentIm.mean()
#misc.imsave("denoised1.png", currentIm * 255)
#misc.imsave("denoised2.png", denoiseIm2 * 255)
#Number candidate regions
#print "Numbering regions"
numberedRegions, maxRegionNum = morph.label(denoiseIm2, 4, 0, return_num = True)
return numberedRegions, scaling
示例12: find_border_centroids
def find_border_centroids(hfp, keys, areas, largeobjkey, disttransfkey, resultkey):
for k, bounds in keys.iteritems():
# bounds = (shp[0],) * 2
for lbl, lblim in hfp['faces', largeobjkey].label_image_iterator(key=k, background=0, area=areas[k]):
hfp.logging('---\nLabel {} found in image {}', lbl, k)
# Avoid very small artifacts
lblim = morphology.opening(lblim)
# Connected component analysis to detect when a label touches the border multiple times
conncomp = vigra.analysis.labelImageWithBackground(lblim.astype(np.uint32), neighborhood=8, background_value=0)
for l in np.unique(conncomp):
# Ignore background
if l == 0: continue
# Get the current label object
curobj = conncomp == l
# Get disttancetransf of the object
curdist = np.array(hfp['faces', disttransfkey, k])
curdist[curobj == False] = 0
# Detect the global maximum of this object
amax = np.amax(curdist)
curdist[curdist < amax] = 0
curdist[curdist > 0] = lbl
# Only one pixel is allowed to be selected
bds = lib.find_bounding_rect(curdist)
centroid = (int((bds[1][0] + bds[1][1]-1) / 2), int((bds[0][0] + bds[0][1]-1) / 2))
# Now translate the calculated centroid to the position within the orignial 3D volume
centroidm = (centroid[0] - bounds, centroid[1] - bounds)
# hfp.logging('centroidxy = {}', centroidm)
# Set the pixel
try:
if centroidm[0] < 0 or centroidm[1] < 0:
raise IndexError
else:
if k == 'xyf':
hfp[resultkey][centroidm[0], centroidm[1], 0] = lbl
elif k == 'xyb':
hfp[resultkey][centroidm[0], centroidm[1], -1] = lbl
elif k == 'xzf':
hfp[resultkey][centroidm[0], 0, centroidm[1]] = lbl
elif k == 'xzb':
hfp[resultkey][centroidm[0], -1, centroidm[1]] = lbl
elif k == 'yzf':
hfp[resultkey][0, centroidm[0], centroidm[1]] = lbl
elif k == 'yzb':
hfp[resultkey][-1, centroidm[0], centroidm[1]] = lbl
except IndexError:
pass
示例13: GrayMM
def GrayMM(img,thresh,size):
structElement = morphology.rectangle(size,size)
img[img == -9999] = 0
img = img/5000
img[img < 0] = 0
img[img > 1] = 1
outdata = morphology.opening(img, structElement)
#threshold after bin
imgOut = outdata > 255*thresh/5000
return imgOut
示例14: ROI_binary_mask
def ROI_binary_mask(sample, size=5, ticket=(80, 80, 80)):
# very slow function at resolution 4
PreprocRes = np.copy(sample)
for i in range(3): # RGB
# this one is painfully slow..
PreprocRes[:, :, i] = Preprocessing(sample[:, :, i])
res = combining(PreprocRes)
ticket = FindTicket(sample, ticket)
res = res - ticket
res[res > 0] = 1
res[res < 0] = 0
res = opening(res, disk(size))
return res
示例15: buffer_mask
def buffer_mask(stuff):
stuff_shape = stuff.shape
stuff_buff = np.array(np.copy(stuff))
for x in range(1,stuff_shape[0]):
for y in range(1,stuff_shape[1]):
if stuff[x,y] == False:
if np.count_nonzero(stuff[x-1:x+2,y-1:y+2]) > 4:
# print x,y
stuff_buff[x,y] = True
selem = morphology.disk(1)
stuff_buff = morphology.opening(stuff_buff, selem)
selem = morphology.disk(1)
stuff_buff = morphology.closing(stuff_buff, selem)
return stuff_buff