def edge_LoG(I, sigma):
LoG = laplace(gaussian(I, sigma=sigma), ksize=3)
thres = np.absolute(LoG).mean() * 1.0
output = sp.zeros(LoG.shape)
w = output.shape[1]
h = output.shape[0]
for y in range(1, h - 1):
for x in range(1, w - 1):
patch = LoG[y - 1:y + 2, x - 1:x + 2]
p = LoG[y, x]
maxP = patch.max()
minP = patch.min()
if p > 0:
zeroCross = True if minP < 0 else False
else:
zeroCross = True if maxP > 0 else False
if ((maxP - minP) > thres) and zeroCross:
output[y, x] = 1
#FIXME: It is necesary to define if return the closing of the output or just the output
#return binary_closing(output)
return output
python类gaussian()的实例源码
def get_blend_map(img, att_map, blur=True, overlap=True):
# att_map -= att_map.min()
# if att_map.max() > 0:
# att_map /= att_map.max()
att_map = 1.0 - att_map
att_map = transform.resize(att_map, (img.shape[:2]), order = 3, mode='edge')
# print att_map.shape
if blur:
att_map = filters.gaussian(att_map, 0.02*max(img.shape[:2]))
att_map -= att_map.min()
att_map /= att_map.max()
cmap = plt.get_cmap('jet')
att_map_v = cmap(att_map)
att_map_v = np.delete(att_map_v, 3, 2)
if overlap:
att_map = 1*(1-att_map**0.7).reshape(att_map.shape + (1,))*img + (att_map**0.7).reshape(att_map.shape+(1,)) * att_map_v
return att_map
def color_gmagnitude(img, sigma=None, norm=True, enhance=False):
"""
"""
if sigma is not None:
img = gaussian(img, sigma=sigma, multichannel=True)
dx = np.dstack([sobel_h(img[..., i]) for i in range(img.shape[-1])])
dy = np.dstack([sobel_v(img[..., i]) for i in range(img.shape[-1])])
Jx = np.sum(dx**2, axis=-1)
Jy = np.sum(dy**2, axis=-1)
Jxy = np.sum(dx * dy, axis=-1)
D = np.sqrt(np.abs(Jx**2 - 2 * Jx * Jy + Jy**2 + 4 * Jxy**2))
e1 = (Jx + Jy + D) / 2. # First eigenvalue
magnitude = np.sqrt(e1)
if norm:
magnitude /= magnitude.max()
if enhance:
magnitude = 1 - np.exp(-magnitude**2 / magnitude.mean())
return magnitude.astype(np.float32)
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 TF_elastic_deform(img, alpha=1.0, sigma=1.0):
"""Elastic deformation of images as described in Simard 2003"""
assert len(img.shape) == 3
h, w, nc = img.shape
if nc != 1:
raise NotImplementedError("Multi-channel not implemented.")
# Generate uniformly random displacement vectors, then convolve with gaussian kernel
# and finally multiply by a magnitude coefficient alpha
dx = alpha * gaussian_filter(
(np.random.random((h, w)) * 2 - 1), sigma, mode="constant", cval=0
)
dy = alpha * gaussian_filter(
(np.random.random((h, w)) * 2 - 1), sigma, mode="constant", cval=0
)
# Map image to the deformation mesh
x, y = np.meshgrid(np.arange(h), np.arange(w), indexing='ij')
indices = np.reshape(x+dx, (-1, 1)), np.reshape(y+dy, (-1, 1))
return map_coordinates(img.reshape((h,w)), indices, order=1).reshape(h,w,nc)
def smooth_each(image, sigma):
return filters.gaussian(image, sigma)
def smooth_hsv(image, sigma):
return filters.gaussian(image, sigma)
def blur(sigma=0.1):
def call(x):
x = gaussian(x, sigma=sigma, preserve_range=True, multichannel=True)
return x
return call
def random_blur(sigma=lambda: np.random.random_sample()*1):
def call(x):
x = gaussian(x, sigma=sigma(), preserve_range=True, multichannel=True)
return x
return call
def gaussianFilter(img,sigma=2.,debug=False,axes=None):
"""Applies gaussian filter to image.
Args:
img (numpy.ndarray): Input image.
Keyword Args:
sigma (float): Standard deviation of gaussian kernel applied.
axes (list): List of matplotlib axes used for plotting. If not specified, will generate new ones.
debug (bool): Print debugging messages and show debugging plots.
Returns:
numpy.ndarray: Processed image.
"""
#Grab original image
orgImg=img.copy()
#Apply gaussian filter
try:
img = skifilt.gaussian_filter(img,sigma)
except AttributeError:
img = skifilt.gaussian(img,sigma)
#Debugging plots
if debug:
#Make figure
if axes==None:
fig,axes = pyfrp_plot_module.makeSubplot([2,2],titles=["Original Image", "After gaussian","Histogram Original","Histogram gaussian"],sup="gaussianFilter debugging output")
#Get common range
vmin,vmax=getCommonRange([orgImg,img])
showImgAndHist(orgImg,axes=axes[0:2],vmin=vmin,vmax=vmax)
showImgAndHist(img,axes=axes[2:],vmin=vmin,vmax=vmax)
return img
def __call__(self, img):
sigma = 0.15 + random.random() * 1.15
blurred_img = gaussian(np.array(img), sigma=sigma, multichannel=True)
blurred_img *= 255
return Image.fromarray(blurred_img.astype(np.uint8))
def _range_mask(self, img):
mask = np.all((img >= self._lo) & (img <= self._up), axis=2)
# Smooth the mask.
skm.binary_opening(mask, selem=self._k, out=mask)
return gaussian(mask, 0.8, multichannel=True) != 0
def draw_density_estimation(self, axis, title, samples, cmap):
axis.clear()
axis.set_xlabel(title)
density_estimation = numpy.zeros((self.l_kde, self.l_kde))
for x, y in samples:
if 0 < x < 1 and 0 < y < 1:
density_estimation[int((1-y) / self.resolution)][int(x / self.resolution)] += 1
density_estimation = filters.gaussian(density_estimation, self.bw_kde_)
axis.imshow(density_estimation, cmap=cmap)
axis.xaxis.set_major_locator(pyplot.NullLocator())
axis.yaxis.set_major_locator(pyplot.NullLocator())
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 circle_mask_blurred( img, radius, sig = 20 ):
'''Creates a blurred circle, using supplied image as template for dimensions'''
height, width, ch = img.shape
centre_y = (height-1) / 2.
centre_x = (width-1) / 2.
img_copy = img.copy()
img_copy[:, :, :] = (0.,0.,0.)
rr, cc = draw.circle(centre_y, centre_x, radius, img.shape)
img_copy[rr, cc, :] = (1.,1.,1.)
img_copy = filters.gaussian(img_copy, sigma=sig, mode='nearest', multichannel=True)
return img_copy
def TF_noise(x, magnitude=None, mode='gaussian', mean=0.0):
if mode in ['gaussian', 'speckle']:
return random_noise(x, mode=mode, mean=mean, var=magnitude)
elif mode in ['salt', 'pepper', 's&p']:
return random_noise(x, mode=mode, amount=magnitude)
else:
return random_noise(x, mode=mode)
def TF_blur(x, sigma=0.0, target=None):
return gaussian(x, sigma=sigma, multichannel=True)
def gridsize(original, segdst=SEGMENT_DISTANCE):
global im
# read the image from disk
im = original.copy()
add_image('Original')
# edge detection
im = sobel(im)
# blurring
im = filters.gaussian(im, sigma=5)
# thresholding: convert to binary rage
loc = threshold_local(im, 31)
im = im > loc
if (DEBUG): add_image('Threshold')
# detect straight lines longer than 150px
segs = probabilistic_hough_line(
im,
threshold=30,
line_length=250,
line_gap=7)
#segs = [seg for seg in segs if vertical(seg)]
# draw the segments
im[:] = 0 # set image to black
for seg in segs:
((x1, y1), (x2, y2)) = seg
rr,cc = draw.line(y1,x1,y2,x2)
im[rr, cc] = 1
if (DEBUG): add_image('Hough Lines')
hh, vv = process_segments(segs)
# draw the segments
im[:] = 0 # set image to black
num = 0
for yy in hh:
for yyy in yy:
(_,y),_ = yyy
rr,cc = draw.line(y,0,y,999)
im[rr, cc] = 1
num += 1
for xx in vv:
for xxx in xx:
(x,_),_ = xxx
rr,cc = draw.line(0,x,999,x)
im[rr, cc] = 1
num += 1
if (DEBUG):
add_image('Filtered Segs')
# finally save the result
displ()
return len(vv)-1, len(hh)-1
def threshold(image, *, sigma=0., radius=0, offset=0.,
method='sauvola', smooth_method='Gaussian'):
"""Use scikit-image filters to "intelligently" threshold an image.
Parameters
----------
image : array, shape (M, N, ...[, 3])
Input image, conformant with scikit-image data type
specification [1]_.
sigma : float, optional
If positive, use Gaussian filtering to smooth the image before
thresholding.
radius : int, optional
If given, use local median thresholding instead of global.
offset : float, optional
If given, reduce the threshold by this amount. Higher values
result in fewer pixels above the threshold.
method: {'sauvola', 'niblack', 'median'}
Which method to use for thresholding. Sauvola is 100x faster, but
median might be more accurate.
smooth_method: {'Gaussian', 'TV', 'NL'}
Which method to use for smoothing. Choose from Gaussian smoothing,
total variation denoising, and non-local means denoising.
Returns
-------
thresholded : image of bool, same shape as `image`
The thresholded image.
References
----------
.. [1] http://scikit-image.org/docs/dev/user_guide/data_types.html
"""
if sigma > 0:
if smooth_method.lower() == 'gaussian':
image = filters.gaussian(image, sigma=sigma)
elif smooth_method.lower() == 'tv':
image = restoration.denoise_tv_bregman(image, weight=sigma)
elif smooth_method.lower() == 'nl':
image = restoration.denoise_nl_means(image,
patch_size=round(2 * sigma))
if radius == 0:
t = filters.threshold_otsu(image) + offset
else:
if method == 'median':
footprint = hyperball(image.ndim, radius=radius)
t = ndi.median_filter(image, footprint=footprint) + offset
elif method == 'sauvola':
w = 2 * radius + 1
t = threshold_sauvola(image, window_size=w, k=offset)
elif method == 'niblack':
w = 2 * radius + 1
t = threshold_niblack(image, window_size=w, k=offset)
else:
raise ValueError('Unknown method %s. Valid methods are median,'
'niblack, and sauvola.' % method)
thresholded = image > t
return thresholded