def fun_estrella_cil_vol(tam_base): aux = morphology.star(tam_base[0] / 3) tam_aux = aux.shape Salida_Base = np.zeros((tam_aux[0], tam_aux[1], tam_base[2])) # Slice-wise drawing for i in range(0, tam_base[2] - 1): Salida_Base[:, :, i] = morphology.star(tam_base[0] / 3) return Salida_Base
def _star_kernel(m, n): c = m + m // 2 - n - n // 2 outer_star = star(m) inner_star = np.zeros_like(outer_star) inner_star[c: -c, c: -c] = star(n) outer_weight = 1.0 / (np.sum(outer_star - inner_star)) inner_weight = 1.0 / np.sum(inner_star) bfilter = (outer_weight * outer_star - (outer_weight + inner_weight) * inner_star) return bfilter
def _star_kernel(m, n): c = m + m // 2 - n - n // 2 outer_star = star(m) inner_star = np.zeros_like(outer_star) inner_star[c:-c, c:-c] = star(n) outer_weight = 1.0 / (np.sum(outer_star - inner_star)) inner_weight = 1.0 / np.sum(inner_star) bfilter = (outer_weight * outer_star - (outer_weight + inner_weight) * inner_star) return bfilter
def fun_estrella_rot_vol(tam_base): aux = morphology.star(tam_base / 3) tam_aux = aux.shape Salida_Base = np.zeros((tam_aux[0], tam_aux[0], tam_aux[0])) # I create a star in the center of the volume, wich must be a cube Salida_Base[:, :, tam_base / 2] = morphology.star(tam_base / 3) Salida_aux = Salida_Base # Now I rotate it over its X axis for i in range(0, 360, 1): Salida_Base = Salida_Base + fun_rotar_vol(Salida_aux, 0, i, 0) # Saturate output... Salida_Base[np.where(Salida_Base > 1)] = 1 return Salida_Base
def _threshold_downsample_lvl(self, lvl_img): """Generates thresholded overview image. Args: wsi: An openslide image instance. Returns: A 2D numpy array of binary image """ # calculate the overview level size and retrieve the image downsample_img = lvl_img.convert('HSV') downsample_img = np.array(downsample_img) # dilate image and then threshold the image schannel = downsample_img[:, :, 1] schannel = dilation(schannel, star(3)) schannel = ndimage.gaussian_filter(schannel, sigma=(5, 5), order=0) threshold_global = threshold_otsu(schannel) schannel[schannel > threshold_global] = 255 schannel[schannel <= threshold_global] = 0 #import scipy.misc # check the result #scipy.misc.imsave('outfile.jpg', schannel) return schannel
def erosion(self): image = self.image se = star(5) ero = morphology.erosion(image, se) self.plotResult(ero, 'Erosion') cv2.imwrite('./Results/{}-erosion-star5.png'.format(self.name_file), ero)
def starMask(maskImg, star_size): boxsize = maskImg.get_xsize() maskArray = EMNumPy.em2numpy(maskImg) if (boxsize <= star_size): print "ERROR: star size is larger than the boxsize of particles." sys.exit() #from skimage.morphology import star #Generates a star shaped structuring element that has 8 vertices and is an overlap of square of size 2*a + 1 with its 45 degree rotated version. #The slanted sides are 45 or 135 degrees to the horizontal axis. starArray = star(star_size, dtype=np.uint8) m, n = starArray.shape assert m==n if (m%2 == 0): pad_before = (boxsize - m)/2 pad_after = (boxsize - m)/2 else: pad_before = (boxsize - m)/2 pad_after = (boxsize - m)/2+1 starArrayPad = np.pad(starArray, (pad_before, pad_after), mode='constant') starImg = EMNumPy.numpy2em(starArrayPad) return starImg
def _threshold_downsample_level(self, img): """Generates thresholded overview image. Args: wsi: An openslide image instance. Returns: A 2D numpy array of binary image """ # calculate the overview level size and retrieve the image img_hsv = img.convert('HSV') img_hsv_np = np.array(img_hsv) # dilate image and then threshold the image schannel = img_hsv_np[:, :, 1] mask = np.zeros(schannel.shape) schannel = dilation(schannel, star(3)) schannel = ndimage.gaussian_filter(schannel, sigma=(5, 5), order=0) threshold_global = threshold_otsu(schannel) # schannel[schannel > threshold_global] = 255 # schannel[schannel <= threshold_global] = 0 mask[schannel > threshold_global] = SELECTED mask[schannel <= threshold_global] = BACKGROUND # import scipy.misc # check the result # scipy.misc.imsave('outfile.jpg', schannel) return mask
def create_mask(img): mask = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) mask = normalize(mask, 0.28, 98) mask[mask[:, :] > 0.0] = 1 mask = erosion(mask, star(9)) mask = erosion(mask, disk(9)) return invert(mask)
def seg(img): img_np = np.asarray(img) img_np_g = img_np[:, :, 1] shape = img_np_g.shape mask = np.ones(shape).astype(np.uint8) searched = np.zeros((shape)).astype(np.uint8) coor = [] init_val = 0 def inRange(val): return val >= init_val - 10 and val <= init_val + 10 def addSeed_initVal(): sums = 0 for idx in range(shape[0]): coor.append({'x': idx, 'y': 0}) searched[idx, 0] = 1 sums += img_np_g[idx, 0] return sums / shape[0] def isPixel(x, y): return (x >= 0 and x < shape[0]) and (y >= 0 and y < shape[1]) def deal(x, y): if isPixel(x, y) and not searched[x, y] and inRange(img_np_g[x, y]): coor.append({'x': x, 'y': y}) searched[x, y] = 1 mask[x, y] = 0 init_val = addSeed_initVal() print('init val: %d' % init_val) while coor != []: x = coor[0]['x'] y = coor[0]['y'] if x == 0: deal(x, y) del coor[0] deal(x + 1, y) deal(x, y + 1) deal(x - 1, y) deal(x, y - 1) mask = opening(mask, star(5)) mask = erosion(mask, star(3)) return mask
def Dilation(img, dil=1, device=None): bs = img.shape[0] img = img.detach().cpu().numpy() img_dil = np.zeros_like(img) for i in range(bs): img_dil[i, 0] = binary_dilation(img[i, 0], selem=star(dil)) return torch.tensor(img_dil).to(device) if device else torch.tensor( img_dil)
def threshold_segmentation(img): # calculate the overview level size and retrieve the image img_hsv = img.convert('HSV') img_hsv_np = np.array(img_hsv) # dilate image and then threshold the image schannel = img_hsv_np[:, :, 1] mask = np.zeros(schannel.shape) schannel = dilation(schannel, star(3)) schannel = ndimage.gaussian_filter(schannel, sigma=(5, 5), order=0) threshold_global = threshold_otsu(schannel) mask[schannel > threshold_global] = FOREGROUND mask[schannel <= threshold_global] = BACKGROUND return mask
def objects(): from skimage.morphology import (square, rectangle, diamond, disk, cube, octahedron, ball, octagon, star) from mpl_toolkits.mplot3d import Axes3D # Generate 2D and 3D structuring elements. struc_2d = { "square(15)": square(15), "rectangle(15, 10)": rectangle(15, 10), "diamond(7)": diamond(7), "disk(7)": disk(7), "octagon(7, 4)": octagon(7, 4), "star(5)": star(5) } struc_3d = { "cube(11)": cube(11), "octahedron(5)": octahedron(5), "ball(5)": ball(5) } # Visualize the elements. fig = plt.figure(figsize=(8, 8)) idx = 1 for title, struc in struc_2d.items(): ax = fig.add_subplot(3, 3, idx) ax.imshow(struc, cmap="Paired", vmin=0, vmax=12) for i in range(struc.shape[0]): for j in range(struc.shape[1]): ax.text(j, i, struc[i, j], ha="center", va="center", color="w") ax.set_axis_off() ax.set_title(title) idx += 1 for title, struc in struc_3d.items(): ax = fig.add_subplot(3, 3, idx, projection=Axes3D.name) ax.voxels(struc) ax.set_title(title) idx += 1 fig.tight_layout() plt.show()
def se(self): fig = plt.figure(figsize=(10, 5)) a = fig.add_subplot(1, 3, 1) plt.imshow(disk(5), cmap=plt.cm.gray) a.set_title('Disk 5px ') plt.axis('off') a = fig.add_subplot(1, 3, 2) plt.imshow(square(5), cmap=plt.cm.gray) a.set_title('Square 5px') plt.axis('off') a = fig.add_subplot(1, 3, 3) plt.imshow(star(5), cmap=plt.cm.gray) a.set_title('Star 5px') plt.axis('off') plt.tight_layout() plt.savefig('./Results/se.png') plt.show()
def task1(): img = mimg.imread("bw1.bmp") new_img1 = binary_erosion(img, selem=square(width=30)) new_img2 = binary_erosion(img, selem=rectangle(width=30, height=20)) new_img3 = binary_erosion(img, selem=diamond(radius=5)) new_img4 = binary_erosion(img, selem=disk(radius=15)) new_img5 = binary_erosion(img, selem=star(a=10)) new_img6 = binary_erosion(img, selem=octagon(m=10, n=20)) new_img7 = binary_dilation(img, ) fig, ax = plt.subplots(1, 8) show(ax[0], img, "original") show(ax[1], new_img1, "BE square") show(ax[2], new_img2, "BE rectangle") show(ax[3], new_img3, "BE diamond") show(ax[4], new_img4, "BE disk") show(ax[5], new_img5, "BE star") show(ax[6], new_img6, "BE octagon") show(ax[7], new_img2, "binary_dilation") plt.show()
def __init__(self, images_dir, masks_dir, img_transform, mask_transform, test=False, sample_size=(1024, 1024), dil=star(0), inv=False, preprocessing_fn=None): self.images_dir = images_dir self.masks_dir = masks_dir self.images_titles = sorted(os.listdir(self.images_dir)) self.masks_titles = sorted(os.listdir(self.masks_dir)) self.img_transform = img_transform self.mask_transform = mask_transform self.preprocessing_fn = preprocessing_fn self.sample_size = sample_size self.test = test self.dil = dil self.inv = inv
def generate_labels(mask_gt, mask_p, sigma=0.5, tr=1): ''' Generate labels for discriminator input ''' gt_dil = binary_dilation(mask_gt,selem=star(1)) skel_gt = make_skeleton(mask_gt, sigma=sigma, tr=tr) T_0 = gt_dil * mask_p labels0 = torch.zeros((8,8)) for i in range(8): for j in range(8): prop_patch = T_0[i*32:(i+1)*32, j*32:(j+1)*32] patch = np.array(skel_gt[i*32:(i+1)*32, j*32:(j+1)*32], dtype=np.uint8) paths = find_paths(patch) labels0[i,j] = assing_label(prop_patch, paths) labels = [labels0] for i in range(3): labels.append(generate_sublabels(labels[-1])) return labels
def binarize_image(image): edges = canny(image/255., sigma=0.001) fullim = closing(edges, selem=star(1)) filled_im = binary_fill_holes(fullim) clean_im2 = remove_small_objects(filled_im, min_size=350) # implementation of watershed padw = 150 cleanpad = pad(clean_im2, ((padw, padw),), mode='constant') distance = ndi.distance_transform_edt(cleanpad) local_maxi = peak_local_max(distance, indices=False, footprint=np.ones((90, 90)), labels=cleanpad) markers = ndi.label(local_maxi)[0] labels = watershed(-distance, markers, mask=cleanpad) labels = labels[padw:-padw, padw:-padw] label_edge = scharr(labels) label_edge = label_edge < 0.0000000000001 split_cells = np.logical_and(label_edge, clean_im2) split_cells = remove_small_objects(split_cells, min_size=350) return split_cells
def find_objects(imgs, masks, filenames): for i, img in enumerate(imgs): temp = rgb2gray(img) edges = canny(temp, mask=masks[i], sigma=2) labeled_image, num_labels = label(edges, return_num=True) remove_obj = remove_small_objects(labeled_image) boundaries = find_boundaries(remove_obj) temp = ndi.binary_closing(boundaries, star(1)) temp = ndi.binary_fill_holes(temp) labeled_image, num_labels = label(temp, return_num=True) remove_obj = remove_small_objects(labeled_image, 1000) remove_obj, num_labels = label(remove_obj, return_num=True) regions = regionprops(remove_obj) remove_obj = ndi.binary_erosion(remove_obj, square(2)) remove_obj = ndi.binary_erosion(remove_obj, disk(2)) # additional removing for case, when small object were receive after erosion remove_obj = remove_small_objects(remove_obj, 1000) remove_obj, num_labels = label(remove_obj, return_num=True) contours = find_contours(remove_obj, 0.9, fully_connected='high') # Display the image and plot all contours found fig, ax = plt.subplots() ax.imshow(imgs[i], interpolation='nearest', cmap=plt.cm.gray) for n, contour in enumerate(contours): ax.plot(contour[:, 1], contour[:, 0], linewidth=1) compact_value = regions[n].area / (regions[n].perimeter)**2 if compact_value > 0.07 and regions[n].solidity > 0.985: continue if compact_value > 0.06 and regions[ n].solidity > 0.985 and regions[n].eccentricity > 0.8: continue if regions[n].solidity > 0.95: added_text = 'C' tolerance_value = 7 else: added_text = '' tolerance_value = 5.5 res = approximate_polygon(contour, tolerance=tolerance_value) text = 'P' + str(len(res) - 1) + added_text coords = regions[n].centroid ax.text(coords[1] - 10, coords[0] - 10, text, style='italic', color='red', fontsize=8, bbox={ 'facecolor': 'white', 'alpha': 0.5, 'pad': 3 }) ax.plot(res[:, 1], res[:, 0], linewidth=2) out_filename = filenames[i][:-4] + '_out.png' fig.savefig(out_filename) ax.axis('image') ax.set_xticks([]) ax.set_yticks([]) plt.show()
128, 192, 0, 128, 64, 128, 128, 192, 128, 128, 0, 64, 0, 128, 64, 0, 0, 192, 0, 128, 192, 0, 0, 64, 128 ] zero_pad = 256 * 3 - len(palette) for i in range(zero_pad): palette.append(0) selems = [ sm.square(7), sm.square(15), sm.square(23), sm.disk(7), sm.disk(15), sm.disk(23), sm.star(7), sm.star(15), sm.star(23) ] def colorize_mask(mask): # mask: numpy array of the mask new_mask = Image.fromarray(mask.astype(np.uint8)).convert('P') new_mask.putpalette(palette) return new_mask def make_dataset(mode): assert mode in ['train', 'val', 'test']
from skimage.morphology import binary_erosion, binary_dilation, binary_opening, binary_closing, square, rectangle, disk, star from skimage import io import matplotlib.pyplot as plt path = "images/lab5/bw2.bmp" image = io.imread(path) openingBin = [] closingBin = [] opening = [] closing = [] salems = [square(5), rectangle(3, 5), disk(3), star(3)] for i in range(4): # binary_opening # binary_closing openingBin.insert(i, binary_opening(image, salems[i])) closingBin.insert(i, binary_closing(openingBin[i], salems[i])) # opening # closing newImage = binary_erosion(image, salems[i]) newImage = binary_dilation(newImage, salems[i]) opening.insert(i, newImage) newImage = binary_dilation(opening[i], salems[i]) newImage = binary_erosion(newImage, salems[i]) closing.insert(i, newImage) plt.gray()
def create_mask(img): img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = normalize(img) img = contrast(img, 0.0) img = erosion(img, star(3)) return invert(img)
tamaño = 10 img = imread('circunferencias.png') noisy_image = rgb2gray(img) binaria = 0.25 <= noisy_image binaria = ~binaria # Erosion y dilatación if opcion == 0: erosionada = erosion(binaria, disk(tamaño)) imagen_final = dilation(erosionada, disk(tamaño)) if opcion == 1: erosionada = erosion(binaria, octagon(tamaño, int(tamaño / 2))) imagen_final = dilation(erosionada, octagon(tamaño, int(tamaño / 2))) if opcion == 2: erosionada = erosion(binaria, square(tamaño)) imagen_final = dilation(erosionada, square(tamaño)) if opcion == 3: erosionada = erosion(binaria, star(tamaño)) imagen_final = dilation(erosionada, star(tamaño)) #Gaurdado de imagenes plt.imshow(binaria, cmap='gray', vmin=0, vmax=1) plt.title('Binaria') plt.show() plt.imshow(erosionada, cmap='gray', vmin=0, vmax=1) plt.title('Tratada') plt.show() plt.imshow(imagen_final, cmap='gray', vmin=0, vmax=1) plt.title('Tratada') plt.show() cv2.imwrite('imagen.png', imagen_final)
max(0, y - box_size):y + box_size, max(0, x - box_size):x + box_size]) #copy is critical out[out != val] = 0 return out.astype('uint8') if __name__ == '__main__': #goal is to generate noise, ask if objects are linear or spherical and exclude based on some feature dims = (1, 500, 500, 500) #choice of obejct selem = ball(9) selem = cube(9) selem = cylinder(9, 9) selem = np.asarray([star(9) for xx in range(9)]) #dilate src = dilate_with_element( generate_random_points(dims, numpoints=20)[0], selem) lbl = ndi.label(src) centers = ndi.measurements.center_of_mass(src, lbl[0], range(1, lbl[1] + 1)) plt.imshow(np.max(src, 0)) plt.imshow(np.max(lbl[0], 0)) ## lbl_vol = np.copy(lbl[0]) lbl_vol[lbl[0] > 0] = 1 sitk.Show(sitk.GetImageFromArray(lbl_vol))
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from skimage.morphology import (square, rectangle, diamond, disk, cube, octahedron, ball, octagon, star) # Generate 2D and 3D structuring elements. struc_2d = { "square(15)": square(15), "rectangle(15, 10)": rectangle(15, 10), "diamond(7)": diamond(7), "disk(7)": disk(7), "octagon(7, 4)": octagon(7, 4), "star(5)": star(5) } struc_3d = { "cube(11)": cube(11), "octahedron(5)": octahedron(5), "ball(5)": ball(5) } # Visualize the elements. fig = plt.figure(figsize=(8, 8)) idx = 1 for title, struc in struc_2d.items(): ax = fig.add_subplot(3, 3, idx) ax.imshow(struc, cmap="Paired", vmin=0, vmax=12)
def dilation(self): image = self.image se = star(5) dil = morphology.dilation(image, se) self.plotResult(dil, 'Dilation')
def element(self) -> np.array: return morphology.star(self.a)
plt.imshow(np.hstack([255 - img, 255 - img_e, 255 - img_d]), cmap='gray') plt.title( "disk(5), iteration: " + str(i + 1), { 'fontsize': 28, 'fontweight': 'bold', 'verticalalignment': 'baseline', 'horizontalalignment': 'center' }) plt.axis('off') plt.show() img_e = img.copy() img_d = img.copy() for i in range(0, 3): img_e = erosion(img_e.copy(), star(5)) img_d = dilation(img_d.copy(), star(5)) plt.imshow(np.hstack([255 - img, 255 - img_e, 255 - img_d]), cmap='gray') plt.title( "star(5), iteration: " + str(i + 1), { 'fontsize': 28, 'fontweight': 'bold', 'verticalalignment': 'baseline', 'horizontalalignment': 'center' }) plt.axis('off') plt.show() img_e = img.copy() img_d = img.copy() for i in range(0, 3):
def _seg_dfs(self, img): img_np = np.asarray(img) img_np_g = img_np[:, :, 1] shape = img_np_g.shape mask = np.ones(shape).astype(np.uint8) * SELECTED searched = np.zeros((shape)).astype(np.bool) coor = [] init_val = 0 def inRange(val): return val >= init_val - 10 and val <= init_val + 10 def addSeed_initVal(): val1 = img_np_g[:, 0].mean() val2 = img_np_g[0, :].mean() val3 = img_np_g[:, shape[1]-1].mean() val4 = img_np_g[shape[0]-1, 0].mean() val = np.max((val1, val2, val3, val4)) for idx in range(shape[0]): # L coor.append({'x': idx, 'y': 0}) searched[idx, 0] = True # R coor.append({'x': idx, 'y': shape[1]-1}) searched[idx, shape[1]-1] = True for idx in range(shape[1]): # U coor.append({'x': 0, 'y': idx}) searched[0, idx] = True # D coor.append({'x': shape[0]-1, 'y': idx}) searched[shape[0]-1, idx] = True return val def isPixel(x, y): return (x >= 0 and x < shape[0]) and (y >= 0 and y < shape[1]) def deal(x, y): if isPixel(x, y) and not searched[x, y] and inRange(img_np_g[x, y]): coor.append({'x': x, 'y': y}) searched[x, y] = True mask[x, y] = BACKGROUND init_val = addSeed_initVal() # print('init val: %d' % init_val) while coor != []: x = coor[0]['x'] y = coor[0]['y'] if x == 0 or y == 0\ or x == shape[0]-1 or y == shape[1]-1: deal(x, y) del coor[0] deal(x + 1, y) deal(x, y + 1) deal(x - 1, y) deal(x, y - 1) mask = opening(mask, star(5)) # mask = erosion(mask, star(3)) mask = dilation(mask, star(3)) return mask
img = sk.io.imread('teeth.jpg', True) grey = img.copy() img_t = cv2.threshold(255*grey, 160, 170, cv2.THRESH_BINARY_INV)[1] img_tmp = 255 -img_t plt.axis('off') plt.imshow(img_tmp, cmap='gray') plt.show() img_e = binary_dilation(img_t, rectangle(2,3)) img_tmp = 255- 255*img_e plt.imshow(img_tmp, cmap='gray') plt.show() img_e = binary_closing(img_e, rectangle(8,2)) img_tmp = 255- 255*img_e plt.imshow(img_tmp, cmap='gray') plt.show() img_e = binary_dilation(img_e, octagon(10,2)) img_tmp = 255- 255*img_e plt.imshow(img_tmp, cmap='gray') plt.show() img_e = binary_dilation(img_e, star(8)) img_tmp = 255- 255*img_e plt.imshow(img_tmp, cmap='gray') plt.show() for i in range(3): img_e = binary_erosion(img_e, star(3 + i)) img_e = 255- 255*img_e plt.imshow(img_e, cmap='gray') plt.axis('off') plt.show()