def test_denoise_bilateral_multidimensional(): img = np.ones((10, 10, 10, 10)) with pytest.raises(ValueError): restoration.denoise_bilateral(img, multichannel=False) with pytest.raises(ValueError): restoration.denoise_bilateral( img, multichannel=True)
def denoising(astro): noisy = astro + 0.6 * astro.std() * np.random.random(astro.shape) noisy = np.clip(noisy, 0, 1) fig, ax = plt.subplots(nrows=2, ncols=3, figsize=(8, 5), sharex=True, sharey=True, subplot_kw={'adjustable': 'box-forced'}) plt.gray() ax[0, 0].imshow(noisy) ax[0, 0].axis('off') ax[0, 0].set_title('noisy') ax[0, 1].imshow(denoise_tv_chambolle(noisy, weight=0.1, multichannel=True)) ax[0, 1].axis('off') ax[0, 1].set_title('TV') ax[0, 2].imshow(denoise_bilateral(noisy, sigma_range=0.05, sigma_spatial=15)) ax[0, 2].axis('off') ax[0, 2].set_title('Bilateral') ax[1, 0].imshow(denoise_tv_chambolle(noisy, weight=0.2, multichannel=True)) ax[1, 0].axis('off') ax[1, 0].set_title('(more) TV') ax[1, 1].imshow(denoise_bilateral(noisy, sigma_range=0.1, sigma_spatial=15)) ax[1, 1].axis('off') ax[1, 1].set_title('(more) Bilateral') ax[1, 2].imshow(astro) ax[1, 2].axis('off') ax[1, 2].set_title('original') fig.tight_layout() plt.show()
def getSubImages(img, pixels, size): subImages = [] originals = [] for i in range(len(img)): subImageRow = [] originalRow = [] for j in range(len(img[i])): if i % pixels == 0 and j % pixels == 0 and i+size-1 < len(img) and j+size-1 < len(img[i]): subImage = [] for k in range(i, i+size, int(size/20)): line = [] for l in range(j, j+size, int(size/20)): line.append(img[k][l]) subImage.append(line) originalRow.append(subImage) if preprocess == preprocessing.SOBEL: subImage = denoise_bilateral(subImage, sigma_range=0.1, sigma_spatial=15) subImage = sobel(subImage) elif preprocess == preprocessing.HOG: subImage = useHoG(subImage) else: subImage = denoise_bilateral(subImage, sigma_range=0.1, sigma_spatial=15) subImage = sobel(subImage) subImage = useHoG(subImage) subImageRow.append(subImage) if len(subImageRow) > 0: subImages.append(subImageRow) originals.append(originalRow) return subImages, originals
def test_denoise_bilateral_3d(): img = lena # add some random noise img += 0.5 * img.std() * np.random.random(img.shape) img = np.clip(img, 0, 1) out1 = restoration.denoise_bilateral(img, sigma_range=0.1, sigma_spatial=20) out2 = restoration.denoise_bilateral(img, sigma_range=0.2, sigma_spatial=30) # make sure noise is reduced assert img.std() > out1.std() assert out1.std() > out2.std()
def test_denoise_sigma_range_and_sigma_color(): img = checkerboard_gray.copy()[:50,:50] # add some random noise img += 0.5 * img.std() * np.random.rand(*img.shape) img = np.clip(img, 0, 1) out1 = restoration.denoise_bilateral(img, sigma_color=0.1, sigma_spatial=10, multichannel=False) with expected_warnings('`sigma_range` has been deprecated in favor of `sigma_color`. ' 'The `sigma_range` keyword argument will be removed in v0.14'): out2 = restoration.denoise_bilateral(img, sigma_color=0.2, sigma_range=0.1, sigma_spatial=10, multichannel=False) assert_equal(out1, out2)
def test_denoise_bilateral_color(): img = checkerboard.copy() # add some random noise img += 0.5 * img.std() * np.random.rand(*img.shape) img = np.clip(img, 0, 1) out1 = restoration.denoise_bilateral(img, sigma_range=0.1, sigma_spatial=20) out2 = restoration.denoise_bilateral(img, sigma_range=0.2, sigma_spatial=30) # make sure noise is reduced in the checkerboard cells assert img[30:45, 5:15].std() > out1[30:45, 5:15].std() assert out1[30:45, 5:15].std() > out2[30:45, 5:15].std()
def test_denoise_bilateral_color(): img = checkerboard.copy()[:50, :50] # add some random noise img += 0.5 * img.std() * np.random.rand(*img.shape) img = np.clip(img, 0, 1) out1 = restoration.denoise_bilateral(img, sigma_color=0.1, sigma_spatial=10, multichannel=True) out2 = restoration.denoise_bilateral(img, sigma_color=0.2, sigma_spatial=20, multichannel=True) # make sure noise is reduced in the checkerboard cells assert_(img[30:45, 5:15].std() > out1[30:45, 5:15].std()) assert_(out1[30:45, 5:15].std() > out2[30:45, 5:15].std())
def denoise_image(data, type=None): from skimage.restoration import denoise_tv_chambolle, denoise_bilateral if type == "tv": return denoise_tv_chambolle(data, weight=0.2, multichannel=True) return denoise_bilateral(data, sigma_range=0.1, sigma_spatial=15)
def crop_resize_other(img, pixelspacing ): print("image shape {}".format(np.array(img).shape)) xmeanspacing = float(1.25826490244) ymeanspacing = float(1.25826490244) xscale = float(pixelspacing) / xmeanspacing yscale = float(pixelspacing) / ymeanspacing xnewdim = round( xscale * np.array(img).shape[0]) ynewdim = round( yscale * np.array(img).shape[1]) img = transform.resize(img, (xnewdim, ynewdim)) #img = cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX) #img = auto_canny(img) img = denoise_bilateral(img, sigma_range=0.05, sigma_spatial=15) #im = cv2.normalize(im, None, 0, 255, cv2.NORM_MINMAX) #img = img.Canny(im,128,128) """crop center and resize""" if img.shape[0] < img.shape[1]: img = img.T # we crop image from center short_egde = min(img.shape[:2]) yy = int((img.shape[0] - short_egde) / 2) xx = int((img.shape[1] - short_egde) / 2) crop_img = img[yy : yy + short_egde, xx : xx + short_egde] crop_img *= 255 return crop_img.astype("uint8")
def blur_predict(model, X, type="median", filter_size=3, sigma=1.0): if type == "median": blured_X = np.array(list(map(lambda x: ndimage.median_filter(x, filter_size), X))) elif type == "gaussian": blured_X = np.array(list(map(lambda x: ndimage.gaussian_filter(x, filter_size), X))) elif type == "f_gaussian": blured_X = np.array(list(map(lambda x: filters.gaussian_filter(x.reshape((28, 28)), sigma=sigma).reshape(784), X))) elif type == "tv_chambolle": blured_X = np.array(list(map(lambda x: restoration.denoise_tv_chambolle(x.reshape((28, 28)), weight=0.2).reshape(784), X))) elif type == "tv_bregman": blured_X = np.array(list(map(lambda x: restoration.denoise_tv_bregman(x.reshape((28, 28)), weight=5.0).reshape(784), X))) elif type == "bilateral": blured_X = np.array(list(map(lambda x: restoration.denoise_bilateral(np.abs(x).reshape((28, 28))).reshape(784), X))) elif type == "nl_means": blured_X = np.array(list(map(lambda x: restoration.nl_means_denoising(x.reshape((28, 28))).reshape(784), X))) elif type == "none": blured_X = X else: raise ValueError("unsupported filter type", type) return predict(model, blured_X)
def test_denoise_bilateral_nan(): img = np.full((50, 50), np.NaN) # This is in fact an optional warning for our test suite. # Python 3.5 will not trigger a warning. with expected_warnings([r'invalid|\A\Z']): out = restoration.denoise_bilateral(img, multichannel=False) assert_equal(img, out)
def denoise_image(self): """ Abstracted version of denoise_bilateral function. Runs function on raw image using given constants """ return restoration.denoise_bilateral( self.im, sigma_color=self.C['BILATERAL_SIGMA_COLOR'], sigma_spatial=self.C['BILATERAL_SIGMA_SPATIAL'], multichannel=False)
def test_denoise_sigma_range_and_sigma_color(): img = checkerboard_gray.copy()[:50, :50] # add some random noise img += 0.5 * img.std() * np.random.rand(*img.shape) img = np.clip(img, 0, 1) out1 = restoration.denoise_bilateral(img, sigma_color=0.1, sigma_spatial=10, multichannel=False) with expected_warnings( '`sigma_range` has been deprecated in favor of `sigma_color`. ' 'The `sigma_range` keyword argument will be removed in v0.14'): out2 = restoration.denoise_bilateral(img, sigma_color=0.2, sigma_range=0.1, sigma_spatial=10, multichannel=False) assert_equal(out1, out2)
def test_denoise_bilateral_3d_multichannel(): img = np.ones((50, 50, 50)) with expected_warnings(["grayscale"]): result = restoration.denoise_bilateral(img) expected = np.empty_like(img) expected.fill(np.nan) assert_equal(result, expected)
def test_denoise_bilateral_nan(): import sys img = np.full((50, 50), np.NaN) # TODO: This warning is not optional in python3. This should be # made a strict warning when we get to 0.15 with expected_warnings(['invalid|\A\Z']): out = restoration.denoise_bilateral(img, multichannel=False) assert_equal(img, out)
def test_denoise_bilateral_multichannel_deprecation(): img = checkerboard.copy()[:50, :50] # add some random noise img += 0.5 * img.std() * np.random.rand(*img.shape) img = np.clip(img, 0, 1) with expected_warnings(["`multichannel` is a deprecated argument"]): out1 = restoration.denoise_bilateral(img, sigma_color=0.1, sigma_spatial=10, multichannel=True) with expected_warnings(["`multichannel` is a deprecated argument"]): out2 = restoration.denoise_bilateral(img, sigma_color=0.2, sigma_spatial=20, multichannel=True) # make sure noise is reduced in the checkerboard cells assert img[30:45, 5:15].std() > out1[30:45, 5:15].std() assert out1[30:45, 5:15].std() > out2[30:45, 5:15].std()
def test_denoise_bilateral_types(dtype): img = checkerboard_gray.copy()[:50, :50] # add some random noise img += 0.5 * img.std() * np.random.rand(*img.shape) img = np.clip(img, 0, 1) # check that we can process multiple float types out = restoration.denoise_bilateral(img, sigma_color=0.1, sigma_spatial=10, multichannel=False)
def thresh_norm_filt(image,thresh=0,norm=1): from skimage.restoration import denoise_bilateral '''Thresholds image to >0 to get rid of dark current, applies a simple denoise filter, and threshes and renormalizes again Returns the normalized image ''' normed=thresh_norm(image,thresh=thresh,norm=norm, copy=True) filt=denoise_bilateral(normed,multichannel=False) norm=thresh_norm(filt,norm=norm,copy=False) return norm
def test_denoise_bilateral_pad(): """This test checks if the bilateral filter is returning an image correctly padded.""" img = img_as_float(data.chelsea())[100:200, 100:200] img_bil = restoration.denoise_bilateral(img, sigma_color=0.1, sigma_spatial=10, multichannel=True) condition_padding = np.count_nonzero(np.isclose(img_bil, 0, atol=0.001)) assert_equal(condition_padding, 0)
def loop(imgFiles): for f in imgFiles: img = img_as_float(data.load(os.path.join(noisyDir, f))) startTime = time.time() img = denoise_bilateral(img, sigma_color=0.1, sigma_spatial=3, multichannel=True) skimage.io.imsave(os.path.join(denoisedDir, f), img) print("Took %f seconds for %s" % (time.time() - startTime, f))
def bilateral(imagePath, outputPath): warnings.filterwarnings("ignore") imagePath = "" + imagePath color = io.imread(imagePath) img = rgb2gray(color) image = img_as_ubyte(img) cleaned = denoise_bilateral(image, mode='edge') cleaned_uint8 = img_as_ubyte(cleaned) imsave('' + outputPath, cleaned_uint8) cleaned_uint8
def image_features_hog3(img, num_features,orientation,maxcell,maxPixel): image=denoise_bilateral(img, win_size=5, sigma_range=None, sigma_spatial=1, bins=10000, mode='constant', cval=0) thresh = threshold_otsu(image) binary = image > thresh im = resize(binary, (maxPixel, maxPixel)) ##hog scikit transform return image_features_hog_fd(im)
def preprocess_image(self, imagefilename): rgb_image = img_as_ubyte(io.imread(imagefilename)) rgb_image = restoration.denoise_bilateral(rgb_image, multichannel=True) if rgb_image.shape[2] == 3: alpha_channel = np.ones(rgb_image.shape[:-1]) rgba_image = np.dstack((rgb_image, alpha_channel)) else: rgba_image = rgb_image io.imsave(filenames.preprocessed_file(imagefilename), rgba_image)
def image_features_hog3(img, num_features,orientation,maxcell,maxPixel): image=denoise_bilateral(img, win_size=5, sigma_range=None, sigma_spatial=1, bins=10000, mode='constant', cval=0) thresh = threshold_otsu(image) binary = image > thresh im = resize(binary, (maxPixel, maxPixel)) ##hog scikit transform fd= hog(im, orientations=orientation, pixels_per_cell=(maxcell, maxcell), cells_per_block=(1, 1), visualise=False,normalise=True) return fd
def Bilateral_proj(S, image_size, lambda_this): """ This function does the Non local mean projection """ S1 = np.reshape(S[0, :], image_size) S2 = np.reshape(S[1, :], image_size) sm1 = S1.min() + 0.5 sm2 = S2.min() + 0.5 S1 = S1 + sm1 S2 = S2 + sm2 # Nonlocal mean denoising S1 = denoise_bilateral(S1, sigma_spatial=lambda_this, multichannel=False) S2 = denoise_bilateral(S2, sigma_spatial=lambda_this, multichannel=False) S[0, :] = np.reshape(S1, (1, image_size[0] * image_size[1])) - sm1 S[1, :] = np.reshape(S2, (1, image_size[0] * image_size[1])) - sm2 return S
def test_denoise_bilateral_types(dtype): img = checkerboard_gray.copy()[:50, :50] # add some random noise img += 0.5 * img.std() * np.random.rand(*img.shape) img = np.clip(img, 0, 1).astype(dtype) # check that we can process multiple float types out = restoration.denoise_bilateral(img, sigma_color=0.1, sigma_spatial=10, multichannel=False)
def test_denoise_bilateral_color(channel_axis): img = checkerboard.copy()[:50, :50] # add some random noise img += 0.5 * img.std() * np.random.rand(*img.shape) img = np.clip(img, 0, 1) img = np.moveaxis(img, -1, channel_axis) out1 = restoration.denoise_bilateral(img, sigma_color=0.1, sigma_spatial=10, channel_axis=channel_axis) out2 = restoration.denoise_bilateral(img, sigma_color=0.2, sigma_spatial=20, channel_axis=channel_axis) img = np.moveaxis(img, channel_axis, -1) out1 = np.moveaxis(out1, channel_axis, -1) out2 = np.moveaxis(out2, channel_axis, -1) # make sure noise is reduced in the checkerboard cells assert img[30:45, 5:15].std() > out1[30:45, 5:15].std() assert out1[30:45, 5:15].std() > out2[30:45, 5:15].std()
def BF_proc(newimg, backimg, FilterSts, FilterOrder, FilterSelect, back_sbs): if back_sbs == 2 and FilterSts == 2: if FilterSelect == 'Median': ImageFinal = ndimage.median_filter(np.subtract(newimg, backimg), FilterOrder) elif FilterSelect == 'Gaussian': ImageFinal = ndimage.gaussian_filter(np.subtract(newimg, backimg), FilterOrder) elif FilterSelect == 'Uniform': ImageFinal = ndimage.uniform_filter(np.subtract(newimg, backimg), FilterOrder) elif FilterSelect == 'Denoise TV': ImageFinal = denoise_tv_chambolle(np.subtract(newimg, backimg), weight=FilterOrder, multichannel=True) elif FilterSelect == 'Bilateral': ImageFinal = denoise_bilateral(np.subtract(newimg, backimg), sigma_range=FilterOrder, sigma_spatial=15) elif back_sbs == 2 and FilterSts == 0: ImageFinal = np.subtract(newimg, backimg) elif back_sbs == 0 and FilterSts == 2: if FilterSelect == 'Median': ImageFinal = ndimage.median_filter(newimg, FilterOrder) elif FilterSelect == 'Gaussian': ImageFinal = ndimage.gaussian_filter(newimg, FilterOrder) elif FilterSelect == 'Uniform': ImageFinal = ndimage.uniform_filter(newimg, FilterOrder) elif FilterSelect == 'Denoise TV': ImageFinal = denoise_tv_chambolle(newimg, weight=FilterOrder, multichannel=True) elif FilterSelect == 'Bilateral': ImageFinal = denoise_bilateral(newimg, sigma_range=FilterOrder, sigma_spatial=15) elif back_sbs == 0 and FilterSts == 0: ImageFinal = newimg return ImageFinal
def denoiseBilateral(imagen,multichannel): """ -Reemplaza el valor de cada pixel en funcion de la proximidad espacial y radiometrica medida por la funcion Gaussiana de la distancia euclidiana entre dos pixels y con cierta desviacion estandar. -False si la imagen es una escala de grises, sino True """ noisy = img_as_float(imagen) denoise = denoise_bilateral(noisy, 7, 9, 0.08,multichannel) return denoise
def _filter_depth(self, depth): temp = self._fill_in_nans(depth) if temp.max() > 1.0: factor = temp.max() temp /= factor else: factor = 1.0 temp_denoised = \ denoise_bilateral(temp, sigma_range=30, sigma_spatial=4.5) temp_denoised[np.isnan(depth)] = np.nan temp_denoised *= factor return temp_denoised
def findmembranes(arr_raw): '''Morphological operations to find cell membranes from dystrophin channel, or similar''' kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) kernelsm = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)) # Need to check here that the values in arr lie between 0 and 255! arr = np.array(arr_raw, dtype=np.uint8) recipe = [ (cv2.dilate, kernelsm), (cv2.dilate, kernelsm), (cv2.dilate, kernelsm), #(cv2.dilate,kernel), #(cv2.dilate,kernel), #(cv2.erode,kernel), (cv2.erode, kernelsm), (cv2.erode, kernelsm), (cv2.erode, kernelsm) ] #arrf = ndimage.gaussian_filter(arr,0.3) #arrf = cv2.GaussianBlur(arr, ksize=(3,3),sigmaX=0,sigmaY=0) #arrf = cv2.medianBlur(arr,3) #arrf = cv2.bilateralFilter(arr,d=9,sigmaColor=1555,sigmaSpace=1555) #ret,thresh = cv2.threshold(arrf.astype(np.uint8),1,255,cv2.THRESH_BINARY) arrf = restoration.denoise_bilateral(arr, 11, sigma_color=3, sigma_spatial=3, multichannel=False) Image.fromarray(makepseudo(arrf)).show() #glob_thresh = filters.threshold_otsu(arrf) #thresh = np.array(255*(arrf > glob_thresh/2.0),dtype=np.uint8) locthresh = filters.threshold_local(arrf, block_size=21, offset=0) thresh = arrf > (locthresh) Image.fromarray(makepseudo(255 * thresh)).show() threshclean = morphology.remove_small_objects(thresh, 600) Image.fromarray(makepseudo(255 * threshclean)).show() #thresh = morphology.skeletonize(thresh) #Image.fromarray(makepseudo(255*thresh)).show() #thresh = morphology.binary_dilation(thresh) #Image.fromarray(makepseudo(255*thresh)).show() thresh = np.array(255 * thresh, dtype=np.uint8) comb0 = threshorig(arr, thresh) for func, kern in recipe: thresh = func(thresh, kern) Image.fromarray(makepseudo(thresh)).show() ithresh = cv2.bitwise_not(thresh) return ((ithresh, comb0, threshorig(arr, thresh)))
def imageDenoise(self, denoise_method='TV'): if denoise_method == 'TV': return denoise_tv_chambolle(self.altered_image) elif denoise_method == 'bilateral': return denoise_bilateral(self.altered_image, sigma_color=0.05, sigma_spatial=15, multichannel=True) elif denoise_method == 'wavelet': return denoise_wavelet(self.altered_image, multichannel=True) else: print denoise_method, ' is not a valid denoising method choice.'
def bilateral_filter(noisy_images: np.ndarray, noise_std_dev: float, show_progress: bool = False) -> np.ndarray: """ Params: noisy_images: receive noisy_images with shape (IMG, M, N, C), where IMG is the quantity of noisy images with dimensions MxN and C represents the color dimensions, i.e. if the images are colored, C = 3 (RGB), otherwise if C = 1, is grayscale. noise_std_dev: the standart deviation from noise. """ validate_array_input(noisy_images) validate_if_noise_std_dev_is_a_float(noise_std_dev) filtered_images = [] if show_progress: for i in tqdm(range(noisy_images.shape[0])): filtered_images.append( denoise_bilateral(noisy_images[i, :, :, 0], win_size=(3, 3), sigma_color=noise_std_dev, sigma_spatial=noise_std_dev, multichannel=False)) else: for i in range(noisy_images.shape[0]): filtered_images.append( denoise_bilateral(noisy_images[i, :, :, 0], win_size=(3, 3), sigma_color=noise_std_dev, sigma_spatial=noise_std_dev, multichannel=False)) filtered_images = np.array(filtered_images) return filtered_images
def depthFilter(disp): # Filter the depth noisy = disp result = denoise_bilateral(noisy, sigma_color=0.5, sigma_spatial=4, win_size=7, multichannel=False) b = np.percentile(noisy, list(range(100))) a = np.percentile(result, list(range(100))) x = estimate_coef(a, b) result = (result * x[1] + x[0]) return result
def nlm(self): # print('Entrou no non local means') # estimate the noise standard deviation from the noisy image sigma_est = np.mean(estimate_sigma(self.environment, multichannel=False)) # print(f"Estimated noise standard deviation = {sigma_est}") # slow algorithm # denoise = denoise_nl_means(self.environment, h=1.15 * sigma_est, fast_mode=False) denoise = denoise_bilateral(self.environment, win_size=3, sigma_spatial=sigma_est, multichannel=False) denoise = np.reshape(denoise, self.environment.shape) return scale(denoise)
def bilateral_2d_filter(image): """ TODO """ return restoration.denoise_bilateral( image, win_size=None, sigma_color=None, sigma_spatial=1, bins=10000, mode="constant", cval=0, multichannel=False, )
def image_features_resize_thres(img, maxPixel, num_features,imageSize): # X is the feature vector with one row of features per image # consisting of the pixel values a, num_featuresnd our metric X=np.zeros(num_features, dtype=float) image=denoise_bilateral(img, win_size=5, sigma_range=None, sigma_spatial=1, bins=10000, mode='constant', cval=0) thresh = threshold_otsu(image) binary = image > thresh im = resize(binary, (maxPixel, maxPixel)) # Store the rescaled image pixels X[0:imageSize] = np.reshape(im,(1, imageSize)) return X
def register_image_pair(idx, path_img_target, path_img_source, path_out): """ register two images together :param int idx: empty parameter for using the function in parallel :param str path_img_target: path to the target image :param str path_img_source: path to the source image :param str path_out: path for exporting the output :return (str, float): """ start = time.time() # load and denoise reference image img_target = io.imread(path_img_target) img_target = denoise_wavelet(img_target, wavelet_levels=7, multichannel=True) img_target_gray = rgb2gray(img_target) # load and denoise moving image img_source = io.imread(path_img_source) img_source = denoise_bilateral(img_source, sigma_color=0.05, sigma_spatial=2, multichannel=True) img_source_gray = rgb2gray(img_source) # detect ORB features on both images detector_target = ORB(n_keypoints=150) detector_source = ORB(n_keypoints=150) detector_target.detect_and_extract(img_target_gray) detector_source.detect_and_extract(img_source_gray) matches = match_descriptors(detector_target.descriptors, detector_source.descriptors) # robustly estimate affine transform model with RANSAC model, _ = ransac((detector_target.keypoints[matches[:, 0]], detector_source.keypoints[matches[:, 1]]), AffineTransform, min_samples=25, max_trials=500, residual_threshold=0.95) # warping source image with estimated transformations img_warped = warp(img_target, model.inverse, output_shape=img_target.shape[:2]) path_img_warped = os.path.join(path_out, NAME_IMAGE_WARPED % idx) io.imsave(path_img_warped, img_warped) # summarise experiment execution_time = time.time() - start return path_img_warped, execution_time
def _filter(photo, parameter): # scale is 1/8 of the maximum image size scale = max(photo.shape[:2]) / (8 * max(photo.shape[:2])) # parameters have to do with pixel diameter for filter, # and color space smoothing new_pic = denoise_bilateral(photo, int(32 * scale), 50, 10 * scale, multichannel=True) edited = photo + (photo - new_pic) * parameter edited = np.clip(edited, 0, 1) return edited
def deoniseBilateral(): astro = img_as_float(data.astronaut()) astro = astro[220:300, 220:320] imgO = astro.copy() noisy = astro + 0.6 * astro.std() * np.random.random(astro.shape) noisy = np.clip(noisy, 0, 1) imgN = noisy.copy() denoised = denoise_bilateral(noisy, sigma_color=0.05, sigma_spatial=15, multichannel=True) imgR = denoised.copy() return [imgO, imgN, imgR]
def autoenhancing(): global panelA,panelB path = tkFileDialog.askopenfilename() print("AUTO ENHANCE") astro = cv2.imread(path) astro = cv2.cvtColor(astro, cv2.COLOR_BGR2GRAY) img=astro p2, p98 = np.percentile(img, (2, 98)) img_rescale = exposure.rescale_intensity(img, in_range=(p2, p98)) img=img_rescale adapteq = exposure.equalize_adapthist(img, clip_limit=0.03) img=adapteq denoised = denoise_bilateral(img, sigma_color=0.1,sigma_spatial=15, multichannel=False) img=denoised for i in range(len(img)): for j in range(len(img[0])): img[i][j]=255*img[i][j] # convert the images to PIL format... pic1 = Image.fromarray(astro) pic = Image.fromarray(img) # ...and then to ImageTk format image = ImageTk.PhotoImage(pic1) edged = ImageTk.PhotoImage(pic) if panelA is None or panelB is None: # the first panel will store our original image panelA = Label(image=image) panelA.image = image panelA.pack(side="left", padx=10, pady=10) # while the second panel will store the edge map panelB = Label(image=edged) panelB.image = edged panelB.pack(side="right", padx=10, pady=10) # otherwise, update the image panels else: # update the pannels panelA.configure(image=image) panelB.configure(image=edged) panelA.image = image panelB.image = edged
def nldenoise(X): """ Pre-process images that are fed to neural network. :param X: X """ print('Denoising images...') progbar = Progbar(X.shape[0]) # progress bar for pre-processing status tracking for i in range(X.shape[0]): X[i] = denoise_bilateral(X[i], sigma_range=0.05, sigma_spatial=4) progbar.add(1) return X
def apply_bilateral_filtering(img, d=15, sigmacolor=75, sigmacoordinate=75): # Retain original data type orig_dtype = img.pixel_array.dtype # Convert from [0; max] to [0; 1] as it is required by denoise_nl_means upper_bound = np.max(img.pixel_array) img_as_float = img.pixel_array / upper_bound new_img = denoise_bilateral(img_as_float, win_size=d, sigma_color=sigmacolor, sigma_spatial=sigmacoordinate) # Convert back to [0; max] new_img *= upper_bound return new_img.astype(orig_dtype)
def watershed(image): """ the watershed algorithm """ if len(image.shape) != 2: raise TypeError("The input image must be gray-scale ") h, w = image.shape image = cv2.equalizeHist(image) image = denoise_bilateral(image, sigma_range=0.1, sigma_spatial=10) image = rescale_intensity(image) image = img_as_ubyte(image) image = rescale_intensity(image) # com.debug_im(image) _, thres = cv2.threshold(image, 80, 255, cv2.THRESH_BINARY_INV) distance = ndi.distance_transform_edt(thres) local_maxi = peak_local_max(distance, indices=False, labels=thres, min_distance=5) # com.debug_im(thres) # implt = plt.imshow(-distance, cmap=plt.cm.jet, interpolation='nearest') # plt.show() markers = ndi.label(local_maxi, np.ones((3, 3)))[0] labels = ws(-distance, markers, mask=thres) labels = np.uint8(labels) # result = np.round(255.0 / np.amax(labels) * labels).astype(np.uint8) # com.debug_im(result) segments = [] for idx in range(1, np.amax(labels) + 1): indices = np.where(labels == idx) left = np.amin(indices[1]) right = np.amax(indices[1]) top = np.amin(indices[0]) down = np.amax(indices[0]) # region = labels[top:down, left:right] # m = (region > 0) & (region != idx) # region[m] = 0 # region[region >= 1] = 1 region = image[top:down, left:right] cont = Contour(mask=region) cont.lt = [left, top] cont.rb = [right, down] segments.append(cont) return segments
def get_regions(img): denoised=restoration.denoise_bilateral(img.astype('uint16'), # sigma_range=0.01, sigma_spatial=15, multichannel=False) smoothened = filters.median(denoised,np.ones((4,4))) markers = np.zeros(smoothened.shape, dtype=np.uint) # otsu works only for only for multi-channel images # markers[smoothened < filters.threshold_otsu(smoothened)] = 1 # markers[smoothened > filters.threshold_otsu(smoothened)] = 2 markers[smoothened < filters.median(smoothened)] = 1 markers[smoothened > filters.median(smoothened)] = 2 labels = random_walker(smoothened, markers, beta=10, mode='bf') regions= measure.label(labels) return regions, denoised, smoothened,markers
def localToneMap(img,dR=4,filt="bilateral",sigma=6, sr=0.05, ss=15): r = img[:,:,0] g = img[:,:,1] b = img[:,:,2] pixList = [r,g,b] (width,height,_) = img.shape # Intensity -- consider using weighted average?? I = np.mean(pixList, axis=0) # Chrominance Channels chromeChannels = map(lambda x:x/I, pixList) # Log Intensity L = np.log2(I) # bilateral filter if filt == "gaussian": B = ndimage.filters.gaussian_filter(L,sigma) else: B = denoise_bilateral(L,sigma_range=sr, sigma_spatial=ss) # Compute the detail layer: D = L - B offset = np.amax(B) scale = dR / (offset - np.amin(B)) B_Prime = (B - offset*np.ones((width,height))) * scale # Reconstruct the log intensity: O = 2^(B' + D) reconLogIntens = map(lambda x: 2**x, B_Prime + D) # New Colors R',G',B' = O * (R/I, G/I, B/I) newColors = map(lambda x: x * reconLogIntens, chromeChannels) # Gamma Compression/correction newColors = map(gammaCorrect, newColors) img[:,:,0] = newColors[0] img[:,:,1] = newColors[1] img[:,:,2] = newColors[2] return img
def _get_processed_image(self): # read image image = mpimg.imread(self.image_path) mask = image[:,:,1] > 150. image[mask] = 255. #plt.imshow(image) #plt.show() # convert to grayscale image = self.rgb2gray(image) # crop image image = image[100:1000,200:1100] mask = mask[100:1000,200:1100] image = image - np.min(image) image[mask] *= 255. / np.max(image[mask]) if self.filter == True: image = denoise_bilateral(image, sigma_spatial=self.denoise_spatial) if self.denoise == True: image = threshold_adaptive(image, self.block_size, offset=self.offset) return image, mask
def crop_resize(img, pixelspacing, center, size): print("image shape {}".format(np.array(img).shape)) xmeanspacing = float(1.25826490244) ymeanspacing = float(1.25826490244) xscale = float(pixelspacing) / xmeanspacing yscale = float(pixelspacing) / ymeanspacing xnewdim = round( xscale * np.array(img).shape[0]) ynewdim = round( yscale * np.array(img).shape[1]) img = transform.resize(img, (xnewdim, ynewdim)) img = np.uint8(img * 255) #img = cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX) #img = auto_canny(img) img = denoise_bilateral(img, sigma_range=0.05, sigma_spatial=15) #im = cv2.normalize(im, None, 0, 255, cv2.NORM_MINMAX) #img = img.Canny(im,128,128) """crop center and resize""" if img.shape[0] < img.shape[1]: img = img.T # we crop image from center short_egde = min(img.shape[:2]) #yy = int((img.shape[0] - short_egde) / 2) #xx = int((img.shape[1] - short_egde) / 2) #crop_img = img[yy : yy + short_egde, xx : xx + short_egde] # resize to 64, 64 resized_img = None yy = int(center[1] - 64) xx = int(center[0] - 64) if yy > 0 and xx > 0 and (yy+128) < img.shape[0] and xx + 128 < img.shape[1]: resized_img = img[yy : yy + 128, xx : xx + 128] else: yy = int((img.shape[0] - short_egde) / 2) xx = int((img.shape[1] - short_egde) / 2) resized_img = img[yy : yy + 128, xx : xx + 128] resized_img *= 255 return resized_img.astype("uint8")
def _smooth_image(self): from skimage import restoration self._image = restoration.denoise_bilateral(self.image)
def smoothen(img): denoised=restoration.denoise_bilateral(img.astype('uint16'), sigma_range=0.01, sigma_spatial=15) smoothened = filters.median(denoised,np.ones((4,4))) return smoothened
noisy = np.clip(noisy, 0, 1) fig, ax = plt.subplots(nrows=2, ncols=3, figsize=(8, 5)) fig.suptitle('George O. Barros - Noisy redution (scikit-image)') plt.gray() ax[0, 0].imshow(noisy) ax[0, 0].axis('off') ax[0, 0].set_title('noisy') ax[0, 1].imshow(denoise_tv_chambolle(noisy, weight=0.1, multichannel=True)) ax[0, 1].axis('off') ax[0, 1].set_title('TV') ax[0, 2].imshow(denoise_bilateral(noisy, sigma_range=0.05, sigma_spatial=15)) ax[0, 2].axis('off') ax[0, 2].set_title('Bilateral') ax[1, 0].imshow(denoise_tv_chambolle(noisy, weight=0.2, multichannel=True)) ax[1, 0].axis('off') ax[1, 0].set_title('(more) TV') ax[1, 1].imshow(denoise_bilateral(noisy, sigma_range=0.1, sigma_spatial=15)) ax[1, 1].axis('off') ax[1, 1].set_title('(more) Bilateral') ax[1, 2].imshow(lena) ax[1, 2].axis('off') ax[1, 2].set_title('original')
def save_roc_curve(actual_pixel_labels, predicted_pixel_labels): y_actual = actual_pixel_labels.flatten() y_predicted = predicted_pixel_labels.flatten() auc = roc_auc_score(y_actual, y_predicted) fpr, tpr, thresholds = roc_curve(y_actual, y_predicted) plt.figure(figsize=(12, 7)) plt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % auc) plt.plot([0, 1], [0, 1], 'k--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.0]) plt.xlabel('False Positive Rate', fontsize="xx-large") plt.ylabel('True Positive Rate', fontsize="xx-large") plt.title('Receiver Operating Characteristic', fontsize="xx-large") plt.legend(loc="lower right") plt.savefig("results/roc_curve.png") plt.show() return True BILATERAL_FILTERING = False folder = sys.argv[1] actual_pixel_labels, predicted_pixel_labels = np.load("results/" + folder + "/y.npy"), np.load("results/" + folder + "/output.npy") if BILATERAL_FILTERING: predicted_pixel_labels = np.array([denoise_bilateral(im) for im in predicted_pixel_labels]) save_random_images(actual_pixel_labels, predicted_pixel_labels, 3) output_stats(actual_pixel_labels, predicted_pixel_labels) #save_roc_curve(actual_pixel_labels, predicted_pixel_labels)
def test_denoise_bilateral_nan(): img = np.NaN + np.empty((50, 50)) out = restoration.denoise_bilateral(img, multichannel=False) assert_equal(img, out)
def test_denoise_bilateral_zeros(): img = np.zeros((10, 10)) assert_equal(img, restoration.denoise_bilateral(img, multichannel=False))
def test_denoise_bilateral_3d_multichannel(): img = np.ones((50, 50, 50)) with expected_warnings(["grayscale"]): result = restoration.denoise_bilateral(img, multichannel=True) assert_equal(result, img)
def test_denoise_bilateral_3d_grayscale(): img = np.ones((50, 50, 3)) with testing.raises(ValueError): restoration.denoise_bilateral(img, multichannel=False)
def test_denoise_bilateral_constant(): img = np.ones((10, 10)) * 5 assert_equal(img, restoration.denoise_bilateral(img, multichannel=False))