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类binary_dilation()的实例源码
def create_mask(im_arr, erode=0):
if im_arr.shape[2] == 3:
im_arr = rgb2gray(im_arr)
thresh = 0.05
inv_bin = np.invert(im_arr > thresh)
all_labels = measure.label(inv_bin)
# Select largest object and invert
seg_arr = all_labels == 0
if erode > 0:
strel = selem.disk(erode, dtype=np.bool)
seg_arr = binary_erosion(seg_arr, selem=strel)
elif erode < 0:
strel = selem.disk(abs(erode), dtype=np.bool)
seg_arr = binary_dilation(seg_arr, selem=strel)
return seg_arr.astype(np.bool)
preprocessing.py 文件源码
项目:bird-species-classification
作者: johnmartinsson
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def compute_binary_mask_sprengel(spectrogram, threshold):
""" Computes a binary mask for the spectrogram
# Arguments
spectrogram : a numpy array representation of a spectrogram (2-dim)
threshold : a threshold for times larger than the median
# Returns
binary_mask : the binary mask
"""
# normalize to [0, 1)
norm_spectrogram = normalize(spectrogram)
# median clipping
binary_image = median_clipping(norm_spectrogram, threshold)
# erosion
binary_image = morphology.binary_erosion(binary_image, selem=np.ones((4, 4)))
# dilation
binary_image = morphology.binary_dilation(binary_image, selem=np.ones((4, 4)))
# extract mask
mask = np.array([np.max(col) for col in binary_image.T])
mask = smooth_mask(mask)
return mask
def outline_polygons(self, width=EDGE_WIDTH, color=LABEL_EDGE):
from skimage.morphology import binary_dilation, disk
im = np.asarray(self.image).copy()
outset = binary_dilation(im == LABEL_POSITIVE, disk(width / 2))
inset = binary_dilation(im != LABEL_POSITIVE, disk(width - width / 2))
boundary = outset & inset
im[boundary] = color
self.image = Image.fromarray(im)
self.artist = ImageDraw.Draw(self.image)
def split_image_into_sudoku_pieces_adaptive_global(image, otsu_local=False, apply_gaussian=False):
L = image.shape[0]
d = int(np.ceil(L / 9))
dd = d // 5
output = []
if apply_gaussian:
image = gaussian_filter(image, sigma=1.0)
if not otsu_local:
image = to_binary_adaptive(image)
for k in range(9):
this_row = []
start_row_i = max([k * d - dd, 0])
stop_row_i = min([(k + 1) * d + dd, L])
for kk in range(9):
start_col_i = max([kk * d - dd, 0])
stop_col_i = min([(kk + 1) * d + dd, L])
i = image[start_row_i:stop_row_i, start_col_i:stop_col_i].copy()
if otsu_local:
i = to_binary_otsu(i)
i = binary_opening(i)
i = to_binary_otsu(i)
if apply_gaussian:
i = to_binary_otsu(binary_dilation(i))
this_row.append(i)
output.append(this_row)
return output, image
def get_centered_blob(img, border_size=1):
img = to_binary_otsu(img)
blob = _get_most_centered_blob(img)
if blob is None:
blob = _get_most_centered_blob(to_binary_otsu(binary_dilation(img)))
if blob is None:
return None
blob_img = add_border(blob, (28, 28), border_size=border_size)
blob_img = to_binary_otsu(blob_img)
return blob_img
def get_unclassified_defect_region(classified_defect_region, td_detect, radius):
# Expand topological defects by radius
td_region = morphology.binary_dilation((td_detect != 0).astype(np.int), morphology.disk(radius))
# Remove classified region
unclassified_defect_region = np.multiply(td_region, 1 - classified_defect_region)
unclassified_defect_region = morphology.binary_dilation(unclassified_defect_region, morphology.disk(radius))
unclassified_defect_region = morphology.binary_erosion(unclassified_defect_region, morphology.disk(radius))
return unclassified_defect_region
def plot_defect_classifications(bmp, list_of_classified_defects, unclassified_defect_region, td_classify, defect_free_region):
plt.rcParams['figure.figsize'] = (10.0, 10.0);
plt.set_cmap('gray');
fig = plt.figure();
ax = fig.add_subplot(111);
fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None);
# Plot the labeled defect regions on top of the temperature field
bmp[defect_free_region==1.] = 0.5*bmp[defect_free_region==1.] # Defect-free region
txt_out = []
for defect in list_of_classified_defects:
defect_center = centroid(defect['defect_region'])
outline = defect['defect_region'] ^ morphology.binary_dilation(defect['defect_region'],morphology.disk(2))
bmp[outline==1] = 255
txt = ax.annotate(DEFECT_TYPES[defect['defect_type']],(defect_center[0]-5,defect_center[1]), color='white', fontweight='bold', fontsize=10);
txt.set_path_effects([PathEffects.withStroke(linewidth=2, foreground='k')]);
txt_out.append(txt)
unknown_td = np.multiply(unclassified_defect_region, (td_classify != 0).astype(np.int))
bmp[morphology.binary_dilation(unknown_td,morphology.disk(2))==1] = 0
bmp[morphology.binary_dilation(unknown_td,morphology.disk(1))==1] = 255
frame = ax.imshow(bmp);
ax.axis('off');
return fig, ax, frame, txt_out
predict-water.py 文件源码
项目:kaggle-dstl-satellite-imagery-feature-detection
作者: alno
项目源码
文件源码
阅读 28
收藏 0
点赞 0
评论 0
def predict_mask(image_id):
mi = np.load('cache/images/%s_MI.npy' % image_id)
return binary_dilation(mi[1] < 0, disk(3))[np.newaxis, :, :].astype(np.uint8)
def binary_dilation(x, radius=3):
""" Return fast binary morphological dilation of an image.
see `skimage.morphology.binary_dilation <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.binary_dilation>`_.
Parameters
-----------
x : 2D array image.
radius : int for the radius of mask.
"""
from skimage.morphology import disk, binary_dilation
mask = disk(radius)
x = binary_dilation(x, selem=mask)
return x
preprocessing.py 文件源码
项目:bird-species-classification
作者: johnmartinsson
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def compute_binary_mask_lasseck(spectrogram, threshold):
# normalize to [0, 1)
norm_spectrogram = normalize(spectrogram)
# median clipping
binary_image = median_clipping(norm_spectrogram, threshold)
# closing binary image (dilation followed by erosion)
binary_image = morphology.binary_closing(binary_image, selem=np.ones((4, 4)))
# dialate binary image
binary_image = morphology.binary_dilation(binary_image, selem=np.ones((4, 4)))
# apply median filter
binary_image = filters.median(binary_image, selem=np.ones((2, 2)))
# remove small objects
binary_image = morphology.remove_small_objects(binary_image, min_size=32, connectivity=1)
mask = np.array([np.max(col) for col in binary_image.T])
mask = smooth_mask(mask)
return mask
# TODO: This method needs some real testing
preprocessing.py 文件源码
项目:bird-species-classification
作者: johnmartinsson
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def smooth_mask(mask):
""" Smooths a binary mask using 4x4 dilation
# Arguments
mask : the binary mask
# Returns
mask : a smoother binary mask
"""
n_hood = np.ones(4)
mask = morphology.binary_dilation(mask, n_hood)
mask = morphology.binary_dilation(mask, n_hood)
# type casting is a bitch
return mask
def sprengel_binary_mask_from_wave_file(filepath):
fs, x = utils.read_wave_file(filepath)
Sxx = sp.wave_to_amplitude_spectrogram(x, fs)
Sxx_log = sp.wave_to_log_amplitude_spectrogram(x, fs)
# plot spectrogram
fig = plt.figure(1)
subplot_image(Sxx_log, 411, "Spectrogram")
Sxx = pp.normalize(Sxx)
binary_image = pp.median_clipping(Sxx, 3.0)
subplot_image(binary_image + 0, 412, "Median Clipping")
binary_image = morphology.binary_erosion(binary_image, selem=np.ones((4, 4)))
subplot_image(binary_image + 0, 413, "Erosion")
binary_image = morphology.binary_dilation(binary_image, selem=np.ones((4, 4)))
subplot_image(binary_image + 0, 414, "Dilation")
mask = np.array([np.max(col) for col in binary_image.T])
mask = morphology.binary_dilation(mask, np.ones(4))
mask = morphology.binary_dilation(mask, np.ones(4))
# plot_vector(mask, "Mask")
fig.set_size_inches(10, 12)
plt.tight_layout()
fig.savefig(utils.get_basename_without_ext(filepath) + "_binary_mask.png", dpi=100)
def segment_lung_mask(image, speedup=4):
def largest_label_volume(im, bg=-1):
vals, counts = np.unique(im, return_counts=True)
counts = counts[vals != bg]
vals = vals[vals != bg]
if len(counts) > 0:
return vals[np.argmax(counts)]
else:
return None
if speedup>1:
smallImage = transform.downscale_local_mean(image,(1,speedup,speedup));
else:
smallImage = image;
# not actually binary, but 1 and 2.
# 0 is treated as background, which we do not want
binary_image = np.array((smallImage < -320) & (smallImage>-1400), dtype=np.int8)
#return binary_image;
for i, axial_slice in enumerate(binary_image):
axial_slice = 1-axial_slice
labeling = measure.label(axial_slice)
l_max = largest_label_volume(labeling, bg=0)
if l_max is not None: #This slice contains some lung
binary_image[i][(labeling!=l_max)] = 1
# Remove other air pockets insided body
labels = measure.label(binary_image, background=0)
m = labels.shape[0]//2;
check_layers = labels[m-12:m+20:4,:,:];
l_max = largest_label_volume(check_layers, bg=0)
while l_max is not None: # There are air pockets
idx = np.where(check_layers==l_max);
ii = np.vstack(idx[1:]).flatten();
if np.max(ii)>labels.shape[1]-24/speedup or np.min(ii)<24/speedup:
binary_image[labels==l_max] = 0;
labels = measure.label(binary_image, background=0)
m = labels.shape[0]//2;
check_layers = labels[m-12:m+20:4,:,:];
l_max = largest_label_volume(check_layers, bg=0)
else:
binary_image[labels != l_max] = 0
break
if speedup<=1:
return binary_image
else:
res = np.zeros(image.shape,dtype=np.uint8);
for i,x in enumerate(binary_image):
orig = np.copy(x);
x = binary_dilation(x,disk(5))
x = binary_erosion(x,disk(5))
x = np.logical_or(x,orig)
y = transform.resize(x*1.0,image.shape[1:3]);
res[i][y>0.5]=1
return res;