def method_6(mask_img: "Image", down_factor=4) -> "NDArray[np.uint8]": """Downsample => Area_opening (Remove local maxima) => Swap index of GM and WM => Area_opening => Swap index back => Area_closing => Morphological opening => Upsample""" # pylint: disable=invalid-name def swap_GM_WM(arr): """Swap GM and WM in arr (swaps index 1 and index 2)""" arr_1 = (arr == 1) arr[arr == 2] = 1 arr[arr_1] = 2 del arr_1 return arr # pylint: enable=invalid-name width, height = mask_img.width, mask_img.height area_threshold_prop = 0.05 area_threshold = int(area_threshold_prop * width * height // down_factor**2) # Downsample the image mask_arr = np.array( mask_img.resize((width // down_factor, height // down_factor), Image.NEAREST)) del mask_img print('Finish downsampling') # Apply area_opening to remove local maxima with area < 20000 px mask_arr = morphology.area_opening(mask_arr, area_threshold=320000 // down_factor**2) print('Finish area_opening #1') # Swap index of GM and WM mask_arr = swap_GM_WM(mask_arr) print('Finish swapping index') # Apply area_opening to remove local maxima with area < 20000 px mask_arr = morphology.area_opening(mask_arr, area_threshold=320000 // down_factor**2) print('Finish area_opening #2') # Swap index back mask_arr = swap_GM_WM(mask_arr) print('Finish swapping index back') # Apply area_closing to remove local minima with area < 12500 px mask_arr = morphology.area_closing(mask_arr, area_threshold=200000 // down_factor**2) print('Finish area_closing') # Apply remove_small_objects to remove tissue residue with area < 0.05 * width * height tissue_arr = morphology.remove_small_objects(mask_arr > 0, min_size=area_threshold, connectivity=2) mask_arr[np.invert(tissue_arr)] = 0 del tissue_arr print('Finish remove_small_objects') # Apply opening with disk-shaped kernel (r=8) to smooth boundary mask_arr = morphology.opening(mask_arr, selem=morphology.disk(radius=32 // down_factor)) print('Finish morphological opening') # Upsample the output mask_arr = np.array(Image.fromarray(mask_arr).resize((width, height), Image.NEAREST)) print('Finish upsampling') return mask_arr
def image2(): image = rgb2gray(np.asarray(Image.open("magnolia.jpg"))) elevation_map = meijering(image) markers = np.zeros_like(image) markers[image < 0.5] = 1 markers[image > 0.6] = 2 segment = segmentation.watershed(elevation_map, markers) segment=area_opening(segment,area_threshold=3000) segment=closing(segment,disk(5)) segment=erosion(segment) plt.hist(elevation_map, bins = 10) fig, ax = plt.subplots(figsize=(7, 4)) ax.set_title('Elevation Map') plt.imshow(elevation_map,cmap="gray") ax.axis("off") fig, ax = plt.subplots(figsize=(7, 4)) ax.imshow(markers, cmap=plt.cm.nipy_spectral) ax.set_title('markers') fig, ax = plt.subplots(figsize=(7, 4)) ax.set_title('segmentation') plt.imshow(segment,cmap="gray") ax.axis("off") plt.show() return segment
def method_3(mask_img: "Image", down_factor=4) -> "NDArray[np.uint8]": """Downsample => Area_opening followed by area_closing (Remove local maxima and minima) => Upsample""" width, height = mask_img.width, mask_img.height # Downsample the image mask_arr = np.array( mask_img.resize((width // down_factor, height // down_factor), Image.NEAREST)) del mask_img print('Finish downsampling') # Apply area_opening to remove local maxima with area < 200000 px mask_arr = morphology.area_opening(mask_arr, area_threshold=320000 // down_factor**2) print('Finish area_opening') # Apply area_closing to remove local minima with area < 200000 px mask_arr = morphology.area_closing(mask_arr, area_threshold=320000 // down_factor**2) print('Finish area_closing') # Upsample the output mask_arr = np.array(Image.fromarray(mask_arr).resize((width, height), Image.NEAREST)) print('Finish upsampling') return mask_arr
def preenchimentoDeBuracos(img): axs[1].set_title('Imagem com buracos preenchidos') axs[1].set_axis_off() #tira o eixo x e y das imagem que fica na coluna 1 abertura = morphology.area_opening( img, 800, 1) #faz a abertura(kernel=[4,4]) apenas com buracos de tamanho <= 800 axs[1].imshow(greyToRGB(abertura), cmap='gray')
def method_5(mask_img: "Image", down_factor=4) -> "NDArray[np.uint8]": """Downsample => Area_opening (Remove local maxima) => Swap index of GM and WM => Area_opening => Swap index back => Morphological opening => Upsample""" # pylint: disable=invalid-name def swap_GM_WM(arr): """Swap GM and WM in arr (swaps index 1 and index 2)""" arr_1 = (arr == 1) arr[arr == 2] = 1 arr[arr_1] = 2 del arr_1 return arr # pylint: enable=invalid-name width, height = mask_img.width, mask_img.height # Downsample the image mask_arr = np.array( mask_img.resize((width // down_factor, height // down_factor), Image.NEAREST)) del mask_img print('Finish downsampling') # Apply area_opening to remove local maxima with area < 200000 px mask_arr = morphology.area_opening(mask_arr, area_threshold=320000 // down_factor**2) print('Finish area_opening #1') # Swap index of GM and WM mask_arr = swap_GM_WM(mask_arr) print('Finish swapping index') # Apply area_opening to remove local maxima with area < 200000 px mask_arr = morphology.area_opening(mask_arr, area_threshold=320000 // down_factor**2) print('Finish area_opening #2') # Swap index back mask_arr = swap_GM_WM(mask_arr) print('Finish swapping index back') # Apply opening with disk-shaped kernel (r=8) to smooth boundary mask_arr = morphology.opening(mask_arr, selem=morphology.disk(radius=32 // down_factor)) print('Finish morphological opening') # Upsample the output mask_arr = np.array(Image.fromarray(mask_arr).resize((width, height), Image.NEAREST)) print('Finish upsampling') return mask_arr
def areaopening(): global filterimage wate = morphology.area_opening(img, area_threshold=64, connectivity=1, parent=None, tree_traverser=None) filterimage = wate io.imshow(wate) io.show()
def image1(): image= rgb2gray(np.asarray(Image.open("flowers.jpg"))) thresh = threshold_otsu(image) binary = image > thresh binary=area_opening(binary,area_threshold=3000) binary = closing(binary, disk(5)) binary=erosion(binary) plt.imshow(np.asarray(Image.open("flowers.jpg"))) plt.show() return binary
def __call__(self, data): import time predict_start_first = time.time() from deformationcytometer.detection.includes.UNETmodel import UNet import numpy as np import cv2 from skimage.filters import gaussian from skimage.morphology import area_opening from skimage import feature from scipy.ndimage import generate_binary_structure, binary_fill_holes from skimage import morphology from deformationcytometer.detection.includes.regionprops import preprocess, getTimestamp if data["type"] == "start" or data["type"] == "end": yield data return log("2detect", "prepare", 1, data["index"]) data_storage_numpy = self.data_storage.get_stored(data["data_info"]) data_storage_mask_numpy = self.data_storage.get_stored(data["mask_info"]) for i, im in enumerate(data_storage_numpy): f = im ff = f / f.max() * 255 ffl = ff ffl = np.uint8(ffl / ffl.max() * 255) fban = gaussian(f, sigma=1) - gaussian(f, sigma=6) fban = fban - fban.min() fban = np.uint8(fban / fban.max() * 255) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (4, 4)) gradient = cv2.morphologyEx(fban, cv2.MORPH_GRADIENT, kernel) fban = np.uint8(gradient / gradient.max() * 255) edges = feature.canny(fban, sigma=2, low_threshold=0.99, high_threshold=0.99, use_quantiles=True) struct = generate_binary_structure(2, 1) ffil = binary_fill_holes(edges, structure=struct).astype(int) ffil = np.uint8(ffil * 255) mask = area_opening(ffil, area_threshold=600, connectivity=1) import matplotlib.pyplot as plt data_storage_mask_numpy[i] = mask import clickpoints if self.write_clickpoints_masks: with clickpoints.DataFile(data["filename"][:-4] + ".cdb") as cdb: # iterate over all images and return them for mask, index in zip(data_storage_mask_numpy, range(data["index"], data["end_index"])): cdb.setMask(frame=index, data=mask.astype(np.uint8)) data["config"].update({"network": self.network_weights}) log("2detect", "prepare", 0, data["index"]) yield data
def method_2(mask_arr: "NDArray[np.uint8]") -> "NDArray[np.uint8]": """Area_opening followed by area_closing (Remove local maxima and minima)""" # Apply area_opening to remove local maxima with area < 200000 px mask_arr = morphology.area_opening(mask_arr, area_threshold=200000) print('Finish area_opening') # Apply area_closing to remove local minima with area < 200000 px mask_arr = morphology.area_closing(mask_arr, area_threshold=200000) print('Finish area_closing') return mask_arr
def get_contour(im, methode="AC"): """ This function finds a contour in image im using either Active Contour method or the OpenCV native findContours function. INPUT : im : binary image to search the contour in methode : specifies methode to be used to search contour, "AC" for active contours, "CV2" for OpenCV's findContours(). Default is "AC" OUTPUT : im : filtered image used for contour search snake : order point list of the contour """ # Filtering im = median(im, disk(2)) im = area_opening(im, 40) # Active Contours if methode == "AC": # Create a circle used as a seed for active contours s = np.linspace(0, 2 * np.pi, 300) r = 14 + 10 * np.sin(s) c = 14 + 10 * np.cos(s) init = np.array([r, c]).T #initial snake snake = active_contour(im, init, alpha=4, beta=1, gamma=1, w_line=0, w_edge=2, coordinates='rc') # Contour using OpenCV elif methode == "CV2": contours, hierarchy = cv2.findContours(im, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) c = np.array(contours[0]) snake = np.array([c[:, 0, 1], c[:, 0, 0]]).T else: raise Exception("Unkown methode : {}".format(methode)) return im, snake
def findCenters(self, img): u = time.time() img -= morphology.area_opening(img, area_threshold=3500) ##print(time.time()-u) img = morphology.opening(img, morphology.rectangle(19, 1)) img = morphology.opening(img, morphology.rectangle(1, 17)) u = time.time() tim = time.time() img2 = morphology.h_maxima(img, 5) img2 = morphology.dilation(img2, morphology.disk(4)) img2 = label(img2) num_things = round(np.max(img2)) colors_arr = [[] for i in range(num_things)] for i in range(len(img2)): for j in range(len(img2[i])): if round(img2[i][j]) != 0: colors_arr[round(img2[i][j] - 1)].append((i, j)) centers = [] for i in range(len(colors_arr)): count = 0 totalcol = 0 totalrow = 0 for j in colors_arr[i]: totalcol += j[1] totalrow += j[0] count += 1 totalcol /= count totalrow /= count centers.append((int(totalrow), int(totalcol))) ####print(time.time()-u) ##print(time.time()-u) for i in range(4): centers = analysis.find_RL_UD(img, centers) centers = self.clear_near(centers) return centers
def buttonSave(arg): copy = arg[1] imageTemp = arg[2] filterTry = filterVar.get() if (filterTry == 1): copy = cv2.GaussianBlur(copy, (5, 5), 0) elif (filterTry == 2): copy = cv2.Canny(copy, 100, 150) elif (filterTry == 3): copy = filters.roberts(imageTemp) elif (filterTry == 4): copy = filters.sato(imageTemp) elif (filterTry == 5): copy = filters.scharr(imageTemp) elif (filterTry == 6): copy = filters.sobel(imageTemp) elif (filterTry == 7): copy = filters.unsharp_mask(copy, radius=30, amount=3) elif (filterTry == 8): #copy = filters.median(imageTemp, disk(5)) b, g, r = cv2.split(copy) b = filters.median(b, disk(5)) g = filters.median(g, disk(5)) r = filters.median(r, disk(5)) copy = cv2.merge((b, g, r)) elif (filterTry == 9): copy = filters.prewitt(imageTemp) elif (filterTry == 10): copy = filters.rank.modal(imageTemp, disk(5)) flag = 0 if (np.ndim(copy) == 2): flag = 0 else: flag = 1 if (hEsitleme.get() or hGrafik.get()): if (flag): copy = cv2.cvtColor(copy, cv2.COLOR_BGR2GRAY) if (hGrafik.get()): plt.hist(copy.ravel(), 256, [0, 256]) plt.show() if (hEsitleme.get()): copy = cv2.equalizeHist(copy) if (uzaysalVars[0].get()): reScaleRatio = float(uzaysalVarsInputs[0].get()) if (np.ndim(copy) == 3): b, g, r = cv2.split(copy) b = transform.rescale(b, reScaleRatio) g = transform.rescale(g, reScaleRatio) r = transform.rescale(r, reScaleRatio) copy = cv2.merge((b, g, r)) else: copy = transform.rescale(copy, reScaleRatio) if (uzaysalVars[1].get()): resizeY = float(uzaysalVarsInputs[1].get()) resizeX = float(uzaysalVarsInputs[2].get()) if (np.ndim(copy) == 3): b, g, r = cv2.split(copy) b = transform.resize( b, (b.shape[0] // resizeX, b.shape[1] // resizeY), anti_aliasing=True) g = transform.resize( g, (g.shape[0] // resizeX, g.shape[1] // resizeY), anti_aliasing=True) r = transform.resize( r, (r.shape[0] // resizeX, r.shape[1] // resizeY), anti_aliasing=True) copy = cv2.merge((b, g, r)) else: copy = transform.resize( copy, (copy.shape[0] // resizeX, copy.shape[1] // resizeY), anti_aliasing=True) if (uzaysalVars[2].get()): copy = transform.swirl(copy, rotation=0, strength=10, radius=120) if (uzaysalVars[3].get()): copy = transform.rotate(copy, int(uzaysalVarsInputs[3].get()), resize=True) if (uzaysalVars[4].get()): copy = copy[:, ::-1] if (yogunlukVars[0].get() or yogunlukVars[1].get()): if (yogunlukVars[0].get()): startINX = int(yogunlukVars[2].get()) finishINX = int(yogunlukVars[3].get()) copy = exposure.rescale_intensity(copy, in_range=(startINX, finishINX)) if (yogunlukVars[1].get()): startOUTX = int(yogunlukVars[4].get()) finishOUTX = int(yogunlukVars[5].get()) copy = exposure.rescale_intensity(copy, out_range=(startOUTX, finishOUTX)) morfoTry = morfVar.get() morfoGirisN = 0 if (np.ndim(copy) == 3): morfoGirisN = 1 if (morfoTry == 1): if (morfoGirisN): b, g, r = cv2.split(copy) b = morphology.area_closing(b, 128, 9) g = morphology.area_closing(g, 128, 9) r = morphology.area_closing(r, 128, 9) copy = cv2.merge((b, g, r)) else: copy = morphology.area_closing(copy) elif (morfoTry == 2): if (morfoGirisN): b, g, r = cv2.split(copy) b = morphology.area_opening(b, 128, 9) g = morphology.area_opening(g, 128, 9) r = morphology.area_opening(r, 128, 9) copy = cv2.merge((b, g, r)) else: copy = morphology.area_opening(copy) elif (morfoTry == 3): if (morfoGirisN): b, g, r = cv2.split(copy) b = morphology.erosion(b, disk(6)) g = morphology.erosion(g, disk(6)) r = morphology.erosion(r, disk(6)) copy = cv2.merge((b, g, r)) else: copy = morphology.erosion(copy, disk(6)) elif (morfoTry == 4): if (morfoGirisN): b, g, r = cv2.split(copy) b = morphology.dilation(b, disk(6)) g = morphology.dilation(g, disk(6)) r = morphology.dilation(r, disk(6)) copy = cv2.merge((b, g, r)) else: copy = morphology.dilation(copy, disk(6)) elif (morfoTry == 5): if (morfoGirisN): b, g, r = cv2.split(copy) b = morphology.opening(b, disk(6)) g = morphology.opening(g, disk(6)) r = morphology.opening(r, disk(6)) copy = cv2.merge((b, g, r)) else: copy = morphology.opening(copy, disk(6)) elif (morfoTry == 6): if (morfoGirisN): b, g, r = cv2.split(copy) b = morphology.closing(b, disk(6)) g = morphology.opening(g, disk(6)) r = morphology.opening(r, disk(6)) copy = cv2.merge((b, g, r)) else: copy = morphology.opening(copy, disk(6)) elif (morfoTry == 7): if (morfoGirisN): b, g, r = cv2.split(copy) b = morphology.white_tophat(b, disk(6)) g = morphology.white_tophat(g, disk(6)) r = morphology.white_tophat(r, disk(6)) copy = cv2.merge((b, g, r)) else: copy = morphology.white_tophat(copy, disk(6)) elif (morfoTry == 8): if (morfoGirisN): b, g, r = cv2.split(copy) b = morphology.black_tophat(b, disk(6)) g = morphology.black_tophat(g, disk(6)) r = morphology.black_tophat(r, disk(6)) copy = cv2.merge((b, g, r)) else: copy = morphology.black_tophat(copy, disk(6)) elif (morfoTry == 10): if (morfoGirisN): copy = cv2.cvtColor(copy, cv2.COLOR_BGR2GRAY) copy = exposure.rescale_intensity(copy) local_maxima = extrema.local_maxima(copy) label_maxima = measure.label(local_maxima) copy = color.label2rgb(label_maxima, copy, alpha=0.7, bg_label=0, bg_color=None, colors=[(1, 0, 0)]) elif (morfoTry == 9): if (morfoGirisN): copy = cv2.cvtColor(copy, cv2.COLOR_BGR2GRAY) copy = exposure.rescale_intensity(copy) h = 0.05 h_maxima = extrema.h_maxima(copy, h) label_h_maxima = measure.label(h_maxima) copy = color.label2rgb(label_h_maxima, copy, alpha=0.7, bg_label=0, bg_color=None, colors=[(1, 0, 0)]) arg[1] = copy arg[2] = imageTemp cv2.imshow("org", copy) cv2.waitKey(0) cv2.destroyAllWindows() """
cascade = "unet" nslices = 256 crop = (15, 15) verbose = True # In[12]: train = glob.glob(train_path + "*.h5") val = glob.glob(val_path + "*.h5") # undersampling patterns - centered k-space - 100 pre computed patterns var_sampling_mask = np.load(sampling_mask_path) acs = area_opening(var_sampling_mask[0], area_threshold=10, connectivity=1, parent=None, tree_traverser=None) if verbose: print(cascade) print("Domains: ", model_string) print("Model name: ", model_path) print("Weights path: ", weights_path) print("Sampling:", 1.0 * var_sampling_mask.sum() / (var_sampling_mask.size * 0.85)) # 85 % sampling Kz direction print("Train path: ", train_path) print("Validation path: ", val_path) # Replicate sampling mask across number of channels var_sampling_mask = np.repeat(var_sampling_mask[:, :, :, np.newaxis],
predict_labels = predict_probs.argmax(axis=-1) test_mask = np.zeros_like(mask) test_mask[mask == 0] = 1 # plt.figure() # imgplot = plt.imshow(test_mask) # plt.show() print('Predicted labels:') predict_labels[predict_labels == 2] = 0 test_mask[reference == 2] = 0 less_6ha_predict = predict_labels - area_opening( predict_labels.astype('int'), area_threshold=69, connectivity=1) test_mask[less_6ha_predict == 1] = 0 print(np.unique(less_6ha_predict)) ######## Only to see the image the test part predict_total = predict_labels * test_mask test_reference = act_reference * test_mask predict_see = gray2rgb(np.uint(predict_total)) reference_see = gray2rgb(np.uint(test_reference)) cv2.imwrite(fold_dir + '/predict_total_' + str(k) + '.tiff', predict_see) cv2.imwrite(fold_dir + '/test_reference_' + str(k) + '.tiff', reference_see) test_mask_see = gray2rgb(np.uint(test_mask))
plt.imshow(im_raw), plt.show() im_raw = ims[37] plt.imshow(im_raw), plt.show() gr = np.max(np.abs(im_raw - bg), axis=-1) > 20 plt.imshow(gr.astype(np.float32)) plt.show() from scipy import ndimage grc = skm.binary_closing(gr, skm.disk(5)) grc = skm.area_opening(grc, 256) grc = ndimage.binary_fill_holes(grc) plt.imshow(grc.astype(np.float32)) plt.show() # Group the results by image # df_grouped = df.groupby("collage_file") # Extra info to save # df_filename = [""] * len(df) # df_cls = [""] * len(df) # df_campaign = [campaign_name] * len(df) # df_sample = [run_name] * len(df) im_save_dir = os.path.join(source_dir, "new_images")