def test_3d_energy_decrease(): a_black = np.zeros((5, 5, 5)).astype(np.uint8) a_black[2, 2, 2] = 255 a_white = invert(a_black) assert_array_less( meijering(a_black, black_ridges=True).std(), a_black.std()) assert_array_less( meijering(a_white, black_ridges=False).std(), a_white.std()) assert_array_less( sato(a_black, black_ridges=True, mode='reflect').std(), a_black.std()) assert_array_less( sato(a_white, black_ridges=False, mode='reflect').std(), a_white.std()) assert_array_less(frangi(a_black, black_ridges=True).std(), a_black.std()) assert_array_less(frangi(a_white, black_ridges=False).std(), a_white.std()) assert_array_less( hessian(a_black, black_ridges=True, mode='reflect').std(), a_black.std()) assert_array_less( hessian(a_white, black_ridges=False, mode='reflect').std(), a_white.std())
def test_2d_linearity(): a_black = np.ones((3, 3)).astype(np.uint8) a_white = invert(a_black) assert_allclose(meijering(1 * a_black, black_ridges=True), meijering(10 * a_black, black_ridges=True), atol=1e-3) assert_allclose(meijering(1 * a_white, black_ridges=False), meijering(10 * a_white, black_ridges=False), atol=1e-3) assert_allclose(sato(1 * a_black, black_ridges=True), sato(10 * a_black, black_ridges=True), atol=1e-3) assert_allclose(sato(1 * a_white, black_ridges=False), sato(10 * a_white, black_ridges=False), atol=1e-3) assert_allclose(frangi(1 * a_black, black_ridges=True), frangi(10 * a_black, black_ridges=True), atol=1e-3) assert_allclose(frangi(1 * a_white, black_ridges=False), frangi(10 * a_white, black_ridges=False), atol=1e-3) assert_allclose(hessian(1 * a_black, black_ridges=True), hessian(10 * a_black, black_ridges=True), atol=1e-3) assert_allclose(hessian(1 * a_white, black_ridges=False), hessian(10 * a_white, black_ridges=False), atol=1e-3)
def test_3d_linearity(): # Note: last axis intentionally not size 3 to avoid 2D+RGB autodetection # warning from an internal call to `skimage.filters.gaussian`. a_black = np.ones((3, 3, 5)).astype(np.uint8) a_white = invert(a_black) assert_allclose(meijering(1 * a_black, black_ridges=True), meijering(10 * a_black, black_ridges=True), atol=1e-3) assert_allclose(meijering(1 * a_white, black_ridges=False), meijering(10 * a_white, black_ridges=False), atol=1e-3) assert_allclose(sato(1 * a_black, black_ridges=True, mode='reflect'), sato(10 * a_black, black_ridges=True, mode='reflect'), atol=1e-3) assert_allclose(sato(1 * a_white, black_ridges=False, mode='reflect'), sato(10 * a_white, black_ridges=False, mode='reflect'), atol=1e-3) assert_allclose(frangi(1 * a_black, black_ridges=True), frangi(10 * a_black, black_ridges=True), atol=1e-3) assert_allclose(frangi(1 * a_white, black_ridges=False), frangi(10 * a_white, black_ridges=False), atol=1e-3) assert_allclose(hessian(1 * a_black, black_ridges=True, mode='reflect'), hessian(10 * a_black, black_ridges=True, mode='reflect'), atol=1e-3) assert_allclose(hessian(1 * a_white, black_ridges=False, mode='reflect'), hessian(10 * a_white, black_ridges=False, mode='reflect'), atol=1e-3)
def calculate(self, image: np.ndarray, mask: np.ndarray, **kwargs) -> np.ndarray: # imshow(image) # plt.show() stream = kwargs["stream"] progress = kwargs["progress"] lap = maximum(minimum(image, disk(8)), disk(5)) progress.progress(30) # imshow(lap) # plt.show() stream[1].append(lap) stream[0].image(stream[1], width=300) res = meijering(lap) progress.progress(60) # imshow(res) # plt.show() stream[1].append(res) stream[0].image(stream[1], width=300) for i, l in enumerate(res): for j, v in enumerate(l): if v >= 0.15: res[i, j] = 1.0 else: res[i, j] = 0.0 progress.progress(60 + int(40 * ((i + 1) / len(res)))) # imshow(res) # plt.show() # stream[1].append(res) # stream[0].image(stream[1], width=300) return res
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 test_2d_cropped_camera_image(): a_black = crop(camera(), ((206, 206), (206, 206))) a_white = invert(a_black) zeros = np.zeros((100, 100)) ones = np.ones((100, 100)) assert_allclose(meijering(a_black, black_ridges=True), meijering(a_white, black_ridges=False)) assert_allclose(sato(a_black, black_ridges=True), sato(a_white, black_ridges=False)) assert_allclose(frangi(a_black, black_ridges=True), zeros, atol=1e-3) assert_allclose(frangi(a_white, black_ridges=False), zeros, atol=1e-3) assert_allclose(hessian(a_black, black_ridges=True), ones, atol=1 - 1e-7) assert_allclose(hessian(a_white, black_ridges=False), ones, atol=1 - 1e-7)
def test_2d_null_matrix(): a_black = np.zeros((3, 3)).astype(np.uint8) a_white = invert(a_black) zeros = np.zeros((3, 3)) ones = np.ones((3, 3)) assert_equal(meijering(a_black, black_ridges=True), ones) assert_equal(meijering(a_white, black_ridges=False), ones) assert_equal(sato(a_black, black_ridges=True), zeros) assert_equal(sato(a_white, black_ridges=False), zeros) assert_allclose(frangi(a_black, black_ridges=True), zeros, atol=1e-3) assert_allclose(frangi(a_white, black_ridges=False), zeros, atol=1e-3) assert_equal(hessian(a_black, black_ridges=False), ones) assert_equal(hessian(a_white, black_ridges=True), ones)
def meijeringFilter(): global filterimage imgFilter7 = filters.meijering(img, sigmas=range(1, 10, 2), alpha=None, black_ridges=True, mode='reflect', cval=0) filterimage = imgFilter7 io.imshow(imgFilter7) io.show()
def test_3d_null_matrix(): # Note: last axis intentionally not size 3 to avoid 2D+RGB autodetection # warning from an internal call to `skimage.filters.gaussian`. a_black = np.zeros((3, 3, 5)).astype(np.uint8) a_white = invert(a_black) zeros = np.zeros((3, 3, 5)) ones = np.ones((3, 3, 5)) assert_allclose(meijering(a_black, black_ridges=True), zeros, atol=1e-1) assert_allclose(meijering(a_white, black_ridges=False), zeros, atol=1e-1) assert_equal(sato(a_black, black_ridges=True, mode='reflect'), zeros) assert_equal(sato(a_white, black_ridges=False, mode='reflect'), zeros) assert_allclose(frangi(a_black, black_ridges=True), zeros, atol=1e-3) assert_allclose(frangi(a_white, black_ridges=False), zeros, atol=1e-3) assert_equal(hessian(a_black, black_ridges=False, mode='reflect'), ones) assert_equal(hessian(a_white, black_ridges=True, mode='reflect'), ones)
def _apply_meijering_filter(image, sigmas): smoothed = rank.mean_percentile(iamage, disk(5), p0=0.25, p1=0.75) filtered = meijering(smoothed, sigmas=sigmas, black_ridges=False) # Meijering filter always evaluates to high values at the image frame; # we hence set the filtered image to zero at those locations frame = np.ones_like(filtered, dtype=np.bool) d = 2 * np.max(sigmas) + 1 frame[d:-d, d:-d] = False filtered[frame] = np.min(filtered) return filtered
def imageprocessingMeijering(img): from skimage.filters import meijering ret,img_b = cv2.threshold(img.astype(np.uint8), 0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) image = meijering(img_b, sigmas=[2], alpha = 5) skeleton = thin(image.reshape(img.shape[0], img.shape[1])) skeleton = skeleton.astype('uint8') return skeleton
def test_3d_cropped_camera_image(): a_black = crop(camera(), ((200, 212), (100, 312))) a_black = np.dstack([a_black, a_black, a_black]) a_white = invert(a_black) zeros = np.zeros((100, 100, 3)) ones = np.ones((100, 100, 3)) assert_allclose(meijering(a_black, black_ridges=True), meijering(a_white, black_ridges=False)) assert_allclose(sato(a_black, black_ridges=True, mode='reflect'), sato(a_white, black_ridges=False, mode='reflect')) assert_allclose(frangi(a_black, black_ridges=True), zeros, atol=1e-3) assert_allclose(frangi(a_white, black_ridges=False), zeros, atol=1e-3) assert_allclose(hessian(a_black, black_ridges=True, mode='reflect'), ones, atol=1 - 1e-7) assert_allclose(hessian(a_white, black_ridges=False, mode='reflect'), ones, atol=1 - 1e-7)
def hessianRidgeDetector(image: np.array) -> np.array: """Find the ridges in the image Args: image (np.array): image to change Returns: np.array: All the ridges are white in color and the remaining image is black """ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) retImg = meijering(gray) retImg = np.stack((retImg, ) * 3, axis = -1) retImg = (retImg*255).astype(np.uint8) return retImg
def run(params): image_location = params['inputImagePath'] result_location = params['resultPath'] sigma_min = float(params['sigma_min']) sigma_max = float(params['sigma_max']) tCount = int(params['TCount']) zCount = int(params['ZCount']) if not os.path.exists(image_location): print(f'Error: {image_location} does not exist') return image_data = imread(image_location) dims = image_data.shape meijering_image = np.empty_like(image_data) output_data = np.empty_like(image_data) sigmas = np.arange(sigma_min, sigma_max, round((sigma_max - sigma_min) / 5, 1)) if tCount > 1: print('Time series are currently not supported.') return meijering_image = meijering(image_data, sigmas=sigmas, black_ridges=False) # Cropping is performed in 2D to get rid of bright pixels at edges of the image. if zCount > 1: crop_size = max(int(max(list(dims[1:])) / 100), 4) meijering_image[:, 0:crop_size, 0:crop_size] = 0 meijering_image[:, 0:crop_size, -crop_size:] = 0 meijering_image[:, -crop_size:, 0:crop_size] = 0 meijering_image[:, -crop_size:, -crop_size:] = 0 else: crop_size = max(int(max(list(dims)) / 100), 4) meijering_image[0:crop_size, 0:crop_size] = 0 meijering_image[0:crop_size, -crop_size:] = 0 meijering_image[-crop_size:, 0:crop_size] = 0 meijering_image[-crop_size:, -crop_size:] = 0 if image_data.dtype == np.uint16: output_data = img_as_uint(meijering_image) else: output_data = img_as_ubyte(meijering_image) imsave(result_location, output_data)
def sketch(path, type, thumbnail=False): print(type) image = rgb2gray(io.imread(path)) if thumbnail == True: size = (2, 2) else: # size = (image.shape[0] / 200 * 1.6, image.shape[1] / 200 * 1.6) size = (8, 8) if type == 'pencil': edge = filters.sobel(image) color = 'gist_gray_r' elif type == 'grey': edge = filters.meijering(image) color = 'Greys' elif type == 'twilight': edge = filters.sobel(image) color = 'twilight' elif type == 'mono': edge = filters.gaussian(image, sigma=0.4) color = 'gist_gray' else: edge = filters.gaussian(image, sigma=0.4) color = type fig, axes = plt.subplots(ncols=1, sharex=True, sharey=True, figsize=size) axes.imshow(edge, cmap=color) axes.axis('off') if path[:4] == 'http': output_filename = path.split('/')[6] else: output_filename = path.strip('.png') plt.savefig(f'{output_filename}.png', bbox_inches='tight', pad_inches=0) return str(output_filename)
def apply_helper(self, data): return filters.meijering(data, sigmas=self.sigmas)
import os import cv2 from skimage.filters import meijering, sato, frangi, hessian import matplotlib.pyplot as plt from skimage import color from PIL import Image import numpy as np for (path, dir, files) in os.walk("/content/drive/My Drive/imgs"): for file in files: img_path = os.path.join(path, file) img = cv2.imread(img_path, cv2.IMREAD_COLOR) img - cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = color.rgb2gray(img) filtered_img = meijering(img, sigmas = (1,3), black_ridges = False) cmap = plt.cm.gray plt.imshow(filtered_img, cmap=cmap) print(filtered_img) ff = filtered_img * 255 print(filtered_img.shape) mm = Image.fromarray(ff.astype(np.uint8)) # re = Image.fromarray(filtered_img.astype(np.uint8)) path_save_name = "/content/drive/My Drive/filter_imgs/" + file # re.save(path_save_name) mm.save(path_save_name) # install dependencies: !pip install pyyaml==5.1 pycocotools>=2.0.1
def meijering_filter(filename): img = asarray(Image.open(filename)) img = rgb2gray(img) img = filters.meijering(img) plt.imsave(filename, img, cmap="gray") return filename
def gradient_watershed(image: np.ndarray, threshold: np.ndarray, magn: float, debug=False, altMarker=False) -> np.ndarray: '''Function calculates a segmentation map based upon gradient-esques maps and watershedding. Parameters ---------- image : np.ndarray or 2D array Image of object for which to segment threshold : np.ndarray, 2D Binary thresholded image. magn: float Magnification of the image as determined by getMagnification. debug : bool, optional If True then various graphs of the functions intermediate state is plotted. Default is False. Returns ------- labels : np.ndarray, 2D Image which has been segmented and labeled. ''' # create markers based upon Sato filtering # see https://scikit-image.org/docs/stable/api/skimage.filters.html?highlight=sato#skimage.filters.sato if not altMarker: markers = meijering(image, black_ridges=True) else: markers = sato(image, black_ridges=True) # meijring maybe better? markers = img_as_ubyte(markers) tmp = markers.copy() # threshold and mask markers = (markers < 3) * threshold tmpt = markers markers = label(markers) # create array for which the watershed algorithm will fill # based upon the gradient of the image edges = rank.gradient(image, disk(1)) if magn > 1.0: markers = remove_small_objects(markers, min_size=50) edges = -edges segm = watershed(edges, markers) labels = label(segm, connectivity=2) if debug >= 2: debug_fig(image, edges, labels, markers, ["Image", "Edges", "Labels", "markers"], [plt.cm.gray, None, make_random_cmap(), make_random_cmap()], pos=2) return labels
if inverted[x][y] == False: neg_pixles.add((x, y)) pixles = list(pos_pixles) + list(neg_pixles) Y = [1 for x in range(len(pos_pixles))] + [0 for x in range(len(neg_pixles))] #%% generate the features features = [[0 for i in range(7)] for j in range(len(pixles))] features = get_features(gaussian(image), pixles, features, 0) features = get_features(laplace(image), pixles, features, 1) features = get_features(median(image), pixles, features, 2) features = get_features(frangi(image), pixles, features, 3) features = get_features(hessian(image), pixles, features, 4) features = get_features(meijering(image), pixles, features, 5) features = get_features(sato(image), pixles, features, 6) #%% split the data into training and testing X_train, X_test, y_train, y_test = train_test_split(features, Y, test_size=0.30, stratify=Y, random_state=0) #%% train the models model = RandomForestClassifier() model.fit(X_train, y_train) pred = model.predict(X_test)
def run(self, ips, snap, img, para = None): rst =meijering(snap, range(para['start'], para['end'], para['step']), black_ridges=para['bridges']) print('hahaha') img[:] = scale(rst, ips.range[0], ips.range[1])
def run(self, ips, imgs, para=None): IPy.show_img( meijering(imgs, range(para['start'], para['end'], para['step']), black_ridges=para['bridges']), ips.title + '-meijering')
def __process_imgfile(self, x): # A series of filters which are stacked as features for each pixel # These filters are in no way verified # More analysis on what features are important is essential # Read in the image ori = cv2.imread(x, cv2.IMREAD_GRAYSCALE) imageShape = ori.shape # Blur the image as a preprocessing step #ori = cv2.GaussianBlur(ori,(37,37),cv2.BORDER_DEFAULT) # This portion of the code is intended to retrieve both the coordinates # of each pixel and the euclidean distance of each value = ori.flatten() ycoords, xcoords = np.indices(ori.shape).reshape(-1, len(value)) euclidean = self.__euclidean_distance(xcoords, ycoords) # Create list and gaussian filter specifics GAUSSIAN = [] gaussianwidths = np.arange(3, 39, 2, dtype=np.uint8) # Iterate through specified gaussian filter dimensions for width in gaussianwidths: gauss = cv2.GaussianBlur(ori, (width, width), cv2.BORDER_DEFAULT) GAUSSIAN.append(gauss) # Blur the image prior to Laplace operation # then equalize histogram after blur = cv2.GaussianBlur(ori, (5, 5), 0) laplace = cv2.Laplacian(blur, cv2.CV_8U) laplace = cv2.equalizeHist(laplace) # Run sobel filter with 4 different kernel size # in both the x and y direction sobel_x1 = cv2.Sobel(ori, cv2.CV_8U, 1, 0, ksize=1) sobel_y1 = cv2.Sobel(ori, cv2.CV_8U, 0, 1, ksize=1) sobel_x3 = cv2.Sobel(ori, cv2.CV_8U, 1, 0, ksize=3) sobel_y3 = cv2.Sobel(ori, cv2.CV_8U, 0, 1, ksize=3) sobel_x5 = cv2.Sobel(ori, cv2.CV_8U, 1, 0, ksize=5) sobel_y5 = cv2.Sobel(ori, cv2.CV_8U, 0, 1, ksize=5) sobel_x7 = cv2.Sobel(ori, cv2.CV_8U, 1, 0, ksize=7) sobel_y7 = cv2.Sobel(ori, cv2.CV_8U, 0, 1, ksize=7) # Canny edge detection filter canny = cv2.Canny(blur, 50, 100) # Erode the image with different kernel sizes kernel11 = np.ones((11, 11), np.uint8) eroded_11 = cv2.erode(ori, kernel11, iterations=2) kernel5 = np.ones((5, 5), np.uint8) eroded_5 = cv2.erode(ori, kernel5, iterations=2) kernel3 = np.ones((3, 3), np.uint8) eroded_3 = cv2.erode(ori, kernel3, iterations=2) # Defining blurred image and kernel for adaptive thresholding blur = cv2.GaussianBlur(ori, (5, 5), 0) kernel = np.ones((5, 5), np.uint8) # Perform adaptive thresholding adapthresh = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 51, 2) adapthresh = cv2.morphologyEx(adapthresh, cv2.MORPH_OPEN, kernel) # Perform gradient analysis on original image gradient = cv2.morphologyEx(ori, cv2.MORPH_GRADIENT, kernel) # Perform otsu thresholding ret, otsuthresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # Median, scharr, prewitt, gabor, meijering,sato,frangi,hessian and roberts filters # all from skimage median_ = np.array(median(ori)) scharr_ = np.array(scharr(ori)) prewitt_ = np.array(prewitt(ori)) gabor_, _ = np.array(gabor(ori, frequency=20)) meijering_ = np.array(meijering(ori)) sato_ = np.array(sato(ori)) frangi_ = np.array(frangi(ori)) hessian_ = np.array(hessian(ori)) roberts_ = np.array(roberts(ori)) # Calls the membrane_projection function Memprojs = self.__membrane_projection(ori) # Creates a list of images to be returned by the function (this has to be # in the same order as the filternames) filteredimages = [ ori, GAUSSIAN[0], GAUSSIAN[1], GAUSSIAN[2], GAUSSIAN[3], GAUSSIAN[4], GAUSSIAN[5], GAUSSIAN[6], GAUSSIAN[7], GAUSSIAN[8], GAUSSIAN[9], GAUSSIAN[10], GAUSSIAN[11], GAUSSIAN[12], GAUSSIAN[13], GAUSSIAN[14], GAUSSIAN[15], GAUSSIAN[16], GAUSSIAN[17], laplace, sobel_x1, sobel_y1, sobel_x3, sobel_y3, sobel_x5, sobel_y5, sobel_x7, sobel_y7, canny, eroded_11, eroded_5, eroded_3, adapthresh, otsuthresh, gradient, median_, scharr_, prewitt_, roberts_, gabor_, meijering_, sato_, frangi_, hessian_, Memprojs[0], Memprojs[1], Memprojs[2], Memprojs[3], Memprojs[4], Memprojs[5] ] # The filternames which correspond to each of the filtered images from above filternames = [ 'ori', 'gaus1', 'gaus2', 'gaus3', 'gaus4', 'gaus5', 'gaus6', 'gaus7', 'gaus8', 'gaus9', 'gaus10', 'gaus11', 'gaus12', 'gaus13', 'gaus14', 'gaus15', 'gaus16', 'gaus17', 'gaus18', 'laplace', 'sobel_x1', 'sobel_y1', 'sobel_x3', 'sobel_y3', 'sobel_x5', 'sobel_y5', 'sobel_x7', 'sobel_y7', 'canny', 'eroded_11', 'eroded_5', 'eroded_3', 'adapthresh', 'otsuthresh', 'gradient', 'meadian', 'scharr', 'prewitt', 'roberts', 'gabor', 'meijering', 'sato', 'frangi', 'hessian', 'MP Add', 'MP Mean', 'MP STDev', 'MP Med', 'MP Max', 'MP Min' ] logging.debug( "process_imgfile: Process images and return stack of filtered image." ) return filteredimages, filternames, imageShape
def run(self, ips, imgs, para=None): imgs[:] = meijering(imgs, range(para['start'], para['end'], para['step']), black_ridges=para['bridges'])
def filter(original_images, transformation): """ :param original_images: :param transformation: :return: """ nb_images, img_rows, img_cols, nb_channels = original_images.shape transformed_images = [] if (transformation == TRANSFORMATION.filter_sobel): for img in original_images: if (nb_channels == 3): img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img = img.reshape(img_rows, img_cols) img_trans = filters.sobel(img) if (nb_channels == 3): img_trans = cv2.cvtColor(img_trans, cv2.COLOR_GRAY2RGB) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_median): for img in original_images: img_trans = ndimage.median_filter(img, size=3) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_minimum): for img in original_images: img_trans = ndimage.minimum_filter(img, size=3) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_maximum): for img in original_images: img_trans = ndimage.maximum_filter(img, size=3) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_gaussian): for img in original_images: img_trans = ndimage.gaussian_filter(img, sigma=1) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_rank): for img in original_images: img_trans = ndimage.rank_filter(img, rank=15, size=3) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_entropy): for img in original_images: radius = 2 if (nb_channels == 3): radius = 1 img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img = img.reshape(img_rows, img_cols) """ requires values in range [-1., 1.] """ img = (img - 0.5) * 2. """ skimage-entropy function returns values in float64, however opencv only supports float32. """ img_trans = np.float32( filters.rank.entropy(img, disk(radius=radius))) """ rescale back into range [0., 1.] """ img_trans = (img_trans / 2.) + 0.5 if (nb_channels == 3): img_trans = cv2.cvtColor(img_trans, cv2.COLOR_GRAY2RGB) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_roberts): for img in original_images: if (nb_channels == 3): img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img = img.reshape(img_rows, img_cols) img_trans = roberts(img) if (nb_channels == 3): img_trans = cv2.cvtColor(img_trans, cv2.COLOR_GRAY2RGB) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_scharr): for img in original_images: if (nb_channels == 3): img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img = img.reshape(img_rows, img_cols) img_trans = scharr(img) if (nb_channels == 3): img_trans = cv2.cvtColor(img_trans, cv2.COLOR_GRAY2RGB) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_prewitt): for img in original_images: if (nb_channels == 3): img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img = img.reshape(img_rows, img_cols) img_trans = prewitt(img) if (nb_channels == 3): img_trans = cv2.cvtColor(img_trans, cv2.COLOR_GRAY2RGB) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_meijering): for img in original_images: if nb_channels == 1: img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) img_trans = meijering(img, sigmas=[0.01]) if nb_channels == 1: img_trans = img_trans[:, :, 1] transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_sato): for img in original_images: img_trans = sato(img) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_frangi): for img in original_images: img_trans = frangi(img) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_hessian): for img in original_images: img_trans = hessian(img) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_skeletonize): for img in original_images: img = invert(img) img = img.reshape((img_rows, img_cols)) img = skeletonize(img) transformed_images.append(img) elif (transformation == TRANSFORMATION.filter_thin): for img in original_images: img = img.reshape(img_rows, img_cols) img = thin(img, max_iter=100) transformed_images.append(img) else: raise ValueError('{} is not supported.'.format(transformation)) transformed_images = np.stack(transformed_images, axis=0) if (nb_channels == 1): # reshape a 3d to a 4d transformed_images = transformed_images.reshape( (nb_images, img_rows, img_cols, nb_channels)) return transformed_images
def run(img, **args): img = meijering(img, **args) return to_base64(img)
def cleanInputMovie(self, imageToClean, arrayOfValues): if len(imageToClean.shape) == 3: inputImage = cv2.cvtColor(imageToClean, cv2.COLOR_BGR2GRAY) else: inputImage = imageToClean.copy() temp = arrayOfValues # if len(inputImage.shape) == 3: # inputImage = cv2.fastNlMeansDenoisingColored(inputImage) # else: # inputImage = cv2.fastNlMeansDenoising(inputImage) _, inputImage = cv2.threshold(inputImage, temp[0], 255, cv2.THRESH_TOZERO) # cv2.imshow("", inputImage.astype(np.uint8)) # cv2.waitKey(0) # inputImage = cv2.subtract(inputImage, temp[0]) # inputImage = cv2.normalize( # inputImage, None, 0, 255, cv2.NORM_MINMAX # ) # self.rescale(inputImage) _, inputImage = cv2.threshold(inputImage, temp[1], 255, cv2.THRESH_TOZERO_INV) # super_threshold_indices = inputImage > temp[1] # inputImage[super_threshold_indices] = 0 # inputImage = cv2.normalize( # inputImage, None, 0, 255, cv2.NORM_MINMAX # ) # self.rescale(inputImage) # inputImage = morphology.area_opening(inputImage, temp[2]) # inputImage = morphology.flood_fill(inputImage,(1,1),0) # inputImage = cv2.subtract(inputImage, openedImage) # inputImage = cv2.normalize( # inputImage, None, 0, 255, cv2.NORM_MINMAX # ) # self.rescale(inputImage) # if temp[3] != 0: # super_threshold_indices = inputImage > temp[3] # inputImage[super_threshold_indices] = 0 # inputImage = cv2.normalize(inputImage, None, 0, 255, cv2.NORM_MINMAX) if temp[2] != 0: inputImage = filters.meijering(inputImage, black_ridges=False) * 255 inputImage = cv2.normalize(inputImage, None, 0, 255, cv2.NORM_MINMAX) _, inputImage = cv2.threshold(inputImage, temp[3], 255, cv2.THRESH_TOZERO) _, inputImage = cv2.threshold(inputImage, temp[4], 255, cv2.THRESH_TOZERO_INV) inputImage = cv2.normalize(inputImage, None, 0, 255, cv2.NORM_MINMAX) # _, inputImage = cv2.threshold(inputImage, 0.95, 255, cv2.THRESH_TOZERO_INV) # if temp[5] != 0: # inputImage = cv2.subtract(inputImage, temp[5]) # inputImage = cv2.normalize(inputImage, None, 0, 255, cv2.NORM_MINMAX) # # if temp[6] != 0: # super_threshold_indices = inputImage > temp[6] # inputImage[super_threshold_indices] = 0 # inputImage = cv2.normalize(inputImage, None, 0, 255, cv2.NORM_MINMAX) # cv2.imshow("removedObjectsImage", inputImage) # cv2.waitKey(0) # cv2.destroyAllWindows() return inputImage
def run(self, magnitudevolume, phasevolume, imageThreshold, enableScreenshots=0): """ Run the actual algorithm """ #magnitude volume magn_imageData = magnitudevolume.GetImageData() magn_rows, magn_cols, magn_zed = magn_imageData.GetDimensions() magn_scalars = magn_imageData.GetPointData().GetScalars() magn_imageOrigin = magnitudevolume.GetOrigin() magn_imageSpacing = magnitudevolume.GetSpacing() magn_matrix = vtk.vtkMatrix4x4() magnitudevolume.GetIJKToRASDirectionMatrix(magn_matrix) # WRITE PHASE FILE IN NIFTI FORMAT phase_imageData = phasevolume.GetImageData() phase_rows, phase_cols, phase_zed = phase_imageData.GetDimensions() phase_scalars = phase_imageData.GetPointData().GetScalars() # imageOrigin = phasevolume.GetOrigin() # imageSpacing = phasevolume.GetSpacing() # phase_matrix = vtk.vtkMatrix4x4() # phasevolume.GetIJKToRASDirectionMatrix(phase_matrix) #Convert vtk to numpy NumpyArray = numpy_support.vtk_to_numpy(magn_scalars) magnp = NumpyArray.reshape(magn_zed, magn_rows, magn_cols) phase_numpyarray = numpy_support.vtk_to_numpy(phase_scalars) phasep = phase_numpyarray.reshape(phase_zed, phase_rows, phase_cols) #mask mask = magnp > 55 mask1 = np.array(mask) mask1 = mask1.astype(np.uint8) mask1 = mask1.squeeze() phasep = phasep.squeeze() #phase_croppedc phase_cropped = cv2.bitwise_and(phasep, phasep, mask=mask1) phase_cropped = np.expand_dims(phase_cropped, axis=0) node = slicer.vtkMRMLScalarVolumeNode() node.SetName('phase_cropped') slicer.mrmlScene.AddNode(node) slicer.util.updateVolumeFromArray(node, phase_cropped) node.SetOrigin(magn_imageOrigin) node.SetSpacing(magn_imageSpacing) node.SetIJKToRASDirectionMatrix(magn_matrix) node.CreateDefaultDisplayNodes() unwrapped_phase = slicer.vtkMRMLScalarVolumeNode() unwrapped_phase.SetName('unwrapped_phase') slicer.mrmlScene.AddNode(unwrapped_phase) # # Run phase unwrapping module # cli_input = slicer.util.getFirstNodeByName('phase_cropped') cli_output = slicer.util.getNode('unwrapped_phase') cli_params = {'inputVolume': cli_input, 'outputVolume': cli_output} slicer.cli.runSync(slicer.modules.phaseunwrapping, None, cli_params) pu_imageData = unwrapped_phase.GetImageData() pu_rows, pu_cols, pu_zed = pu_imageData.GetDimensions() pu_scalars = pu_imageData.GetPointData().GetScalars() pu_NumpyArray = numpy_support.vtk_to_numpy(pu_scalars) phaseunwrapped = pu_NumpyArray.reshape(pu_zed, pu_rows, pu_cols) I = phaseunwrapped A = np.fft.fft2(I) A1 = np.fft.fftshift(A) # Image size [M, N, O] = A.shape # filter size parameter R = 10 X = np.arange(0, N, 1) Y = np.arange(0, M, 1) # Y = Y.astype(int) [X, Y] = np.meshgrid(X, Y) Cx = 0.5 * N Cy = 0.5 * M Lo = np.exp(-(((X - Cx)**2) + ((Y - Cy)**2)) / ((2 * R)**2)) Hi = 1 - Lo J = A1 * Lo J1 = np.fft.ifftshift(J) B1 = np.fft.ifft2(J1) K = A1 * Hi K1 = np.fft.ifftshift(K) B2 = np.fft.ifft2(K1) B2 = np.real(B2) kernel1 = np.ones((3, 3), np.uint8) kernel = np.ones((5, 5), np.uint8) mask3 = cv2.morphologyEx(mask1, cv2.MORPH_CLOSE, kernel1) mask3 = cv2.erode(mask3, kernel, iterations=7) mask3 = mask3.astype(np.uint8) B2 = cv2.bitwise_and(B2.squeeze(), B2.squeeze(), mask=mask3) meiji = meijering(B2, sigmas=(1, 1), black_ridges=True) (minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc(meiji) # B3 = cv2.circle(B2, maxLoc, 3, (255, 100, 0), 1) circle1 = plt.Circle(maxLoc, 2, color='red') # # plt.imshow(meiji, cmap='gray') # plt.add_artist(circle1) # plt.show() fig, axs = plt.subplots(1, 2) fig.suptitle('Needle Tracking') axs[0].imshow(magnp.squeeze(), cmap='gray') axs[0].set_title('Magnitude + Tracked') axs[0].add_artist(circle1) axs[0].axis('off') axs[1].set_title('Processed Phase Image') axs[1].imshow(meiji, cmap='jet') axs[1].axis('off') plt.savefig("mygraph.png") # plt.show() # B3 = np.expand_dims(B3, axis=0) # final = slicer.vtkMRMLScalarVolumeNode() # final.SetName('final') # slicer.mrmlScene.AddNode(final) # slicer.util.updateVolumeFromArray(final, B3) # final.SetOrigin(magn_imageOrigin) # final.SetSpacing(magn_imageSpacing) # final.SetIJKToRASDirectionMatrix(magn_matrix) # final.CreateDefaultDisplayNodes() print(maxLoc) return True
#ridge detection from skimage import io, filters, feature import matplotlib.pyplot as plt from skimage.color import rgb2gray from skimage.util import invert import cv2 from skimage.filters import meijering, sato, frangi, hessian img = io.imread("Classified image 1.jpg") #img = rgb2gray(invert(img)) img = rgb2gray(img) meijering_img = meijering(img) sato_img = sato(img) frangi_img = frangi(img) hessian_img = hessian(img) fig = plt.figure(figsize=(20, 20)) #ax1 = fig.add_subplot(2,2,1) #ax1.imshow(img, cmap="gray") #ax1.title.set_text("Input Image") ax1 = fig.add_subplot(2, 2, 1) ax1.imshow(hessian_img, cmap="gray") ax1.title.set_text("Hessian") ax2 = fig.add_subplot(2, 2, 2)
# plt.hist(img.flatten(),256,[0,256], color = 'r') # plt.xlim([0,256]) # plt.legend(('cdf','histogram'), loc = 'upper left') # plt.show() # cdf_m = np.ma.masked_equal(cdf,0) # cdf_m = (cdf_m - cdf_m.min())*255/(cdf_m.max()-cdf_m.min()) # cdf = np.ma.filled(cdf_m,0).astype('uint8') # img2 = cdf[img] # # cv2.imshow("ccc", img2) equ = cv2.equalizeHist(img2) q2(equ) # cv2.imshow("bbb", equ) img3 = filters.meijering(equ, sigmas=range(1, 10, 2), alpha=None, black_ridges=True) cv2.imshow("aaa", img3) img4 = np.array(img3) * 255 img4 = img4.astype(np.uint8) #cv2.imwrite("aaa.png", img4) ret3, th3 = cv2.threshold(img4, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # cv2.imshow("ddd", th3) # morphological opening kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) img_binary = cv2.morphologyEx(th3, cv2.MORPH_OPEN, kernel) cv2.imshow("eee", img_binary) cv2.waitKey(0) B = th3.copy()