def plot_img_with_mask(img,mask,mask2=None, line_size=2):
kernel = np.ones((line_size,line_size),dtype=np.uint8)
if np.max(img)<=1.0:
img = np.array(img*255,dtype=np.uint8);
mask = np.array(mask*255, dtype=np.uint8);
color_img = np.dstack((img,img,img));
edges = binary_dilation(canny(mask,sigma=1.0),kernel);
color_img[edges,0] = 255;
color_img[edges,1] = 0;
color_img[edges,2] = 0;
if mask2 is not None:
mask2 = np.array(mask2*255,dtype=np.uint8);
edges2 = binary_dilation(canny(mask2,sigma=1.0),kernel);
color_img[edges2,2] = 255;
color_img[edges2,0:2] = 0;
plt.imshow(color_img)
python类canny()的实例源码
def _extract_lines(img, edges=None, mask=None, min_line_length=20, max_line_gap=3):
global __i__
__i__ += 1
if edges is None:
edges = canny(rgb2grey(img))
if mask is not None:
edges = edges & mask
# figure()
# subplot(131)
# imshow(img)
# subplot(132)
#vimshow(edges)
# subplot(133)
# if mask is not None:
# imshow(mask, cmap=cm.gray)
# savefig('/home/shared/Projects/Facades/src/data/for-labelme/debug/foo/{:06}.jpg'.format(__i__))
lines = np.array(probabilistic_hough_line(edges, line_length=min_line_length, line_gap=max_line_gap))
return lines
def detect_optic_disk(image_rgb, disk_center, out_name):
scale = 100
w_sum = cv2.addWeighted(image_rgb, 4, cv2.GaussianBlur(image_rgb, (0, 0), scale / 30), -4, 128)# * circular_mask + 128 * (1 - circular_mask)
# Image.fromarray(np.mean(w_sum, axis=2).astype(np.uint8)).save(out_name)
edges = canny(np.mean(w_sum, axis=2).astype(np.uint8), sigma=1.,
low_threshold=50.)#, high_threshold=100.)
result = hough_ellipse(edges, threshold=10, min_size=45, max_size=55)
result.sort(order='accumulator')
best = list(result[-1])
yc, xc, a, b = [int(round(x)) for x in best[1:5]]
orientation = best[5]
cy, cx = ellipse_perimeter(yc, xc, a, b, orientation)
image_rgb[cy, cx] = (0, 0, 255)
Image.fromarray(image_rgb).save(out_name)
def cav_edge(img, sigma):
"""
Detect edges in the recovered image.
Reference
=========
[1] Edge detection with canny by python
http://blog.csdn.net/matrix_space/article/details/49786427
Inputs
======
img: np.ndarray
the recovered image
sigma: float
the sigma in canny methods
Output
======
img_edge: np.ndarray
teh edge detected image
"""
# Reprocess of the image
# idx = np.where(img >= 1)
img_re = img
# img_re[idx] = 1
# Edge detect
edge = feature.canny(img_re, sigma=sigma)
# bool to integer
img_edge = edge.astype('int32')
return img_edge
def canny_demo():
# Generate noisy image of a square
im = np.zeros((128, 128))
im[32:-32, 32:-32] = 1
im = ndi.rotate(im, 15, mode='constant')
im = ndi.gaussian_filter(im, 4)
im += 0.2 * np.random.random(im.shape)
# Compute the Canny filter for two values of sigma
edges1 = feature.canny(im)
edges2 = feature.canny(im, sigma=3)
# display results
fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3, figsize=(8, 3),
sharex=True, sharey=True)
ax1.imshow(im, cmap=plt.cm.gray)
ax1.axis('off')
ax1.set_title('noisy image', fontsize=20)
ax2.imshow(edges1, cmap=plt.cm.gray)
ax2.axis('off')
ax2.set_title('Canny filter, $\sigma=1$', fontsize=20)
ax3.imshow(edges2, cmap=plt.cm.gray)
ax3.axis('off')
ax3.set_title('Canny filter, $\sigma=3$', fontsize=20)
fig.tight_layout()
plt.show()
def detect_colored_circles_no_prints(rgb_img, radius_range, hsv_color_ranges):
"""
Detects circles by color as above, without prints.
"""
min_radius, max_radius = radius_range
# convert image to gray
gray_img = rgb2gray(rgb_img)
# find edges in image
edges_img = canny(gray_img, sigma=15.0, low_threshold=0.55, high_threshold=0.8)
# find circles from edge_image
hough_radii, hough_res = find_circles(edges_img, min_radius, max_radius)
#
centers, accums, radii = circles_per_radius(hough_radii, hough_res, number_circles_per_radius=16)
color_coords_dictionary, debug_img = find_circles_by_color(centers, accums, radii, rgb_img, hsv_color_ranges, False)
color_not_found = False
for key, array in color_coords_dictionary.items():
if len(array) == 0: color_not_found = True
if color_not_found:
return None
color_coords = calc_coordinate_averages(color_coords_dictionary)
return color_coords
def check_reg(fixed_img, moved_img, scale=15, norm=True, sigma=0.8, **kwargs):
dim = list(moved_img.shape)
resol = list(moved_img.header['pixdim'][1:4])
# Convert 4D image to 3D or raise error
data = convert_to_3d(moved_img)
# Check normalization
if norm:
data = apply_p2_98(data)
# Set slice axis for mosaic grid
slice_axis, cmap = check_sliceaxis_cmap(data, kwargs)
cmap = 'YlOrRd'
# Set grid shape
data, slice_grid, size = set_mosaic_fig(data, dim, resol, slice_axis, scale)
fig, axes = BrainPlot.mosaic(fixed_img, scale=scale, norm=norm, cmap='bone', **kwargs)
# Applying inversion
invert = check_invert(kwargs)
data = apply_invert(data, *invert)
# Plot image
for i in range(slice_grid[1] * slice_grid[2]):
ax = axes.flat[i]
edge = data[:, :, i]
edge = feature.canny(edge, sigma=sigma) # edge detection for second image
# edge = ndimage.gaussian_filter(edge, 3)
mask = np.ones(edge.shape)
sx = ndimage.sobel(edge, axis=0, mode='constant')
sy = ndimage.sobel(edge, axis=1, mode='constant')
sob = np.hypot(sx, sy)
mask[sob == False] = np.nan
m_norm = colors.Normalize(vmin=0, vmax=1.5)
if i < slice_grid[0] and False in np.isnan(mask.flatten()):
ax.imshow(mask.T, origin='lower', interpolation='nearest', cmap=cmap, norm=m_norm, alpha=0.8)
else:
ax.imshow(np.zeros((dim[0], dim[1])).T, origin='lower', interpolation='nearest', cmap='bone')
ax.set_axis_off()
fig.set_facecolor('black')
if notebook_env:
display(fig)
return fig, axes
def process(self, im):
(width, height, _) = im.image.shape
img_adapted = im.prep(self.transform)
if width > self.max_resized or height > self.max_resized:
scale_height = self.max_resized / height
scale_width = self.max_resized / width
scale = min(scale_height, scale_width)
img_adapted = resize(img_adapted, (int(width * scale), int(height * scale)))
edges = canny(img_adapted, sigma=self.sigma)
# Detect two radii
# Calculate image diameter
shape = im.image.shape
diam = math.sqrt(shape[0] ** 2 + shape[1] ** 2)
radii = np.arange(diam / 3, diam * 0.8, 2)
hough_res = hough_circle(edges, radii)
accums = []
for radius, h in zip(radii, hough_res):
# For each radius, extract two circles
peaks = peak_local_max(h, num_peaks=1, min_distance=1)
if len(peaks) > 0:
accums.extend(h[peaks[:, 0], peaks[:, 1]])
if len(accums) == 0: # TODO: fix, should not happen
return [0]
idx = np.argmax(accums)
return [accums[idx]]
def run(self, ips, snap, img, para = None):
return feature.canny(snap, sigma=para['sigma'], low_threshold=para[
'low_threshold'], high_threshold=para['high_threshold'], mask=ips.get_msk())*255
def detect_edges(filename):
"""Return a normalized gray scale image."""
LOGGER.debug(filename)
image = rgb2grey(imread(filename)) # rgb2gray can be a noop
image = image / image.max()
return canny(image, sigma=CANNY_SIGMA)
def main():
"""Load image, apply Canny, plot."""
img = skiutil.img_as_float(data.camera())
img = filters.gaussian_filter(img, sigma=1.0)
sobel_y = np.array([
[-1, -2, -1],
[0, 0, 0],
[1, 2, 1]
])
sobel_x = np.rot90(sobel_y) # rotates counter-clockwise
img_sx = signal.correlate(img, sobel_x, mode="same")
img_sy = signal.correlate(img, sobel_y, mode="same")
g_magnitudes = np.sqrt(img_sx**2 + img_sy**2) / np.sqrt(2)
g_orientations = np.arctan2(img_sy, img_sx)
g_mag_nonmax = non_maximum_suppression(g_magnitudes, g_orientations)
canny = hysteresis(g_mag_nonmax, 0.35, 0.05)
ground_truth = feature.canny(data.camera())
util.plot_images_grayscale(
[img, g_magnitudes, g_mag_nonmax, canny, ground_truth],
["Image", "After Sobel", "After nonmax", "Canny", "Canny (Ground Truth)"]
)
def is_boarder(patch, sigma):
"""
this function evaluates the canny filter ovet the passed patch
returning through boolean
wheather or not the image can be catalogued as boarder retrieving the
boolean value of the center
:param patch: the image to filter
:param sigma: sigma value for the canny filter
:return: boolean value
"""
bool_patch = canny( patch, sigma=sigma )
return bool_patch[patch.shape[0] / 2][patch.shape[1] / 2]
def __init__(self, num_samples=None, path_to_images=None, sigma=None,
patch_size=(23, 23),
augmentation_angle=0):
"""
load and store all necessary information to achieve the patch extraction
:param num_samples: number of patches required
:param path_to_images: path to the folder containing all '.png.' files
:param sigma: sigma value to apply at the canny filter for patch extraction criteria
:param patch_size: dimensions for each patch
:param augmentation_angle: angle necessary to operate the increase of the number of patches
"""
print( '*' * 50 )
print( 'Starting patch extraction...' )
# inserire il check per sigma
if sigma is None:
print( " missing threshold value, impossible to proceed" )
exit( 1 )
if path_to_images is None:
ValueError( 'no destination file' )
exit( 1 )
if num_samples is None:
ValueError( 'specify the number of patches to extract and reload class' )
exit( 1 )
self.sigma = sigma
self.augmentation_angle = augmentation_angle % 360
self.images = np.array( [rgb2gray( imread( path_to_images[el] ).astype( 'float' ).reshape( 5, 216, 160 )[-2] )
for el in range( len( path_to_images ) )] )
if self.augmentation_angle is not 0:
self.augmentation_multiplier = int( 360. / self.augmentation_angle )
else:
self.augmentation_multiplier = 1
self.num_samples = num_samples
self.patch_size = patch_size
def analyze_image(args):
"""Analyze all wells from all trays in one image."""
filename, config = args
LOGGER.debug(filename)
rows = config["rows"]
columns = config["columns"]
well_names = config["well_names"]
name = splitext(basename(filename))[0]
if config["parse_dates"]:
try:
index = convert_to_datetime(fix_date(name))
except ValueError as err:
return {"error": str(err), "filename": filename}
else:
index = name
try:
image = rgb2grey(imread(filename))
except OSError as err:
return {"error": str(err), "filename": filename}
plate_images = cut_image(image)
data = dict()
for i, (plate_name, plate_image) in enumerate(
zip(config["plate_names"], plate_images)):
plate = data[plate_name] = dict()
plate[config["index_name"]] = index
if i // 3 == 0:
calibration_plate = config["left_image"]
positions = config["left_positions"]
else:
calibration_plate = config["right_image"]
positions = config["right_positions"]
try:
edge_image = canny(plate_image, CANNY_SIGMA)
offset = align_plates(edge_image, calibration_plate)
# Add the offset to get the well centers in the analyte plate
well_centers = generate_well_centers(
np.array(positions) + offset, config["plate_size"], rows,
columns)
assert len(well_centers) == rows * columns
plate_image /= (1 - plate_image + float_info.epsilon)
well_intensities = [find_well_intensity(plate_image, center)
for center in well_centers]
for well, intensity in zip(well_names, well_intensities):
plate[well] = intensity
except (AttributeError, IndexError) as err:
return {"error": str(err), "filename": filename}
return data
def compute_edgelets(image, sigma=3):
"""Create edgelets as in the paper.
Uses canny edge detection and then finds (small) lines using probabilstic
hough transform as edgelets.
Parameters
----------
image: ndarray
Image for which edgelets are to be computed.
sigma: float
Smoothing to be used for canny edge detection.
Returns
-------
locations: ndarray of shape (n_edgelets, 2)
Locations of each of the edgelets.
directions: ndarray of shape (n_edgelets, 2)
Direction of the edge (tangent) at each of the edgelet.
strengths: ndarray of shape (n_edgelets,)
Length of the line segments detected for the edgelet.
"""
gray_img = color.rgb2gray(image)
edges = feature.canny(gray_img, sigma)
lines = transform.probabilistic_hough_line(edges, line_length=3,
line_gap=2)
locations = []
directions = []
strengths = []
for p0, p1 in lines:
p0, p1 = np.array(p0), np.array(p1)
locations.append((p0 + p1) / 2)
directions.append(p1 - p0)
strengths.append(np.linalg.norm(p1 - p0))
# convert to numpy arrays and normalize
locations = np.array(locations)
directions = np.array(directions)
strengths = np.array(strengths)
directions = np.array(directions) / \
np.linalg.norm(directions, axis=1)[:, np.newaxis]
return (locations, directions, strengths)