def test_richardson_lucy_deprecated_iterations_kwarg(): psf = np.ones((5, 5)) / 25 data = convolve2d(test_img, psf, 'same') np.random.seed(0) data += 0.1 * data.std() * np.random.standard_normal(data.shape) with expected_warnings(["`iterations` is a deprecated argument"]): restoration.richardson_lucy(data, psf, iterations=5)
def dogonvole(image, psf, gpu_algorithm, kernel=(2., 2., 0.), blur=(0.9, 0.9, 0.), niter=10, use_gpu=1): """ Perform deconvolution and difference of gaussian processing. Parameters ---------- image : ndarray psf : ndarray kernel : tuple blur : tuple niter : int Returns ------- image : ndarray Processed image same shape as image input. """ global hot_pixels if not psf.sum() == 1.: raise ValueError("psf must be normalized so it sums to 1") image = image.astype('float32') imin = image.min() border =1 for y, x in hot_pixels: y_min = y-border x_min = x-border y_max = y+border x_max = x+border if y-1<=border: y_min=0 if x-1<=border: x_min=0 if y+1>=2048-border: y_max=2048 if x+1>=2048-border: x_max=2048 image[y, x] = np.average(image[y_min:y_max, x_min:x_max]); img_bg = gaussian(image, kernel[:len(image.shape)], preserve_range=True) image = numpy.subtract(image, img_bg) numpy.place(image, image<0, 1./2**16) image = image.astype('uint16') if len(image.shape)==3: for i in range(image.shape[2]): if use_gpu==1: image[:,:,i] = gpu_algorithm.run(fd_data.Acquisition(data=image[:,:,i], kernel=psf), niter=niter).data else: image[:,:,i] = restoration.richardson_lucy(image[:,:,i], psf,niter, clip=False) elif len(image.shape)==2: if use_gpu==1: image = gpu_algorithm.run(fd_data.Acquisition(data=image, kernel=psf), niter=niter).data else: image = restoration.richardson_lucy(image, psf, niter, clip=False) else: raise ValueError('image is not a supported dimensionality.') image = gaussian(image, blur[:len(image.shape)], preserve_range=True) return image
def dogonvole(image, psf, kernel=(2., 2., 0.), blur=(1.2, 1.2, 0.), niter=20): """ Perform deconvolution and difference of gaussian processing. Parameters ---------- image : ndarray psf : ndarray kernel : tuple blur : tuple niter : int Returns ------- image : ndarray Processed image same shape as image input. """ global hot_pixels, use_gpu, gpu_algorithm if not psf.sum() == 1.: raise ValueError("psf must be normalized so it sums to 1") image = image.astype('float32') imin = image.min() for y, x in hot_pixels: image[y, x] = imin img_bg = ndimage.gaussian_filter(image, kernel[:len(image.shape)]) image = numpy.subtract(image, img_bg) numpy.place(image, image < 0, 1. / 2**16) image = image.astype('uint16') if len(image.shape) == 3: for i in range(image.shape[2]): if use_gpu == 1: image[:, :, i] = gpu_algorithm.run(fd_data.Acquisition(data=image, kernel=psf), niter=niter).data else: image[:, :, i] = restoration.richardson_lucy(image[:, :, i], psf, niter, clip=False) elif len(image.shape) == 2: if use_gpu == 1: image = gpu_algorithm.run(fd_data.Acquisition(data=image, kernel=psf), niter=niter).data else: image = restoration.richardson_lucy(image, psf, niter, clip=False) else: raise ValueError('image is not a supported dimensionality.') image = ndimage.gaussian_filter(image, blur[:len(image.shape)]) return image
def deconvolve_psf(self, method='WH'): self.full_map.meta['lvl_num'] = 1.4 if method == 'WH': self.full_map.data = restoration.unsupervised_wiener(self.full_map.data.astype('float64'), self.psf.astype('float64'), clip=False)[0] if method == 'RL_SSW': # should be equivalent to the IDL AIA_DECONVOLVE_RICHARDSONLUCY() routine but it isn't # Not working... image = self.full_map.data.astype(np.float) im_deconv = np.copy(self.full_map.data.astype(np.float)) psf = self.psf.astype(np.float) psf_mirror = psf[::-1, ::-1] # to make the correlation easier psfnorm = fftconvolve(psf, np.ones_like(psf), 'same') for _ in range(25): relative_blur = image / fftconvolve(psf, im_deconv, 'same') im_deconv *= fftconvolve(relative_blur, psf_mirror, 'same')/psfnorm self.full_map.data=np.abs(im_deconv) if method == 'RL': # Not working... self.full_map.data = restoration.richardson_lucy(self.full_map.data.astype('float64'), self.psf.astype('float64'), iterations=25, clip=False)
def preprocess(self, image): # convert to gray scale at first gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # compute the Laplacian of the image and then return the focus # measure, which is simply the variance of the Laplacian fm = cv2.Laplacian(gray, cv2.CV_64F).var() if fm < self.thres: self.blurred = True # if blurred, remove blurry via Wiener filter if self.blurred: from scipy.signal import convolve2d from skimage import color, data, restoration img = color.rgb2gray(image) psf = np.ones((5, 5)) / 25 img = convolve2d(gray, psf, 'same') img += 0.1 * img.std() * np.random.standard_normal(img.shape) deconvolved_img = restoration.richardson_lucy(img, psf, 5, clip=False) # #deconvolved_img = restoration.wiener(img, psf, 50, clip=False) # deconvolved_img, _ = restoration.unsupervised_wiener(img, psf, # clip=False) # # print(deconvolved_img) return deconvolved_img else: return image
def deconvolve(self, psf, iterations): ''' Method for deconvolution of convolved 2d data by using Richardson-Lucy algorithm :param psf: tuple(float(Gaussian kernel length), float(Gaussian kernel sigma)) 2d array, point spread function :param iterations: int, number of iterations :return: 2d array, convolved data ''' def gkern(kernlen=psf[0], nsig=psf[1]): """Returns a 2D Gaussian kernel array.""" interval = (2 * nsig + 1.) / (kernlen) x = np.linspace(-nsig - interval / 2., nsig + interval / 2., kernlen + 1) kern1d = np.diff(st.norm.cdf(x)) kernel_raw = np.sqrt(np.outer(kern1d, kern1d)) kernel = kernel_raw / kernel_raw.sum() return kernel if type(psf) == tuple: current_psf = gkern() else: current_psf = psf self.dehazed_image = restoration.richardson_lucy(self.dehazed_image, current_psf, iterations=iterations, clip=False)
def psfmatch(psf_sharp, psf_broad, kernelname, method='fft', window=window_default, iterations=30): """Derive the kernel that matches psf_sharp to psf_broad""" psf1 = fits.getdata(psf_sharp) psf2 = fits.getdata(psf_broad) assert psf1.shape[0] % 2 == 1 assert psf2.shape[0] % 2 == 1 assert psf1.shape[0] == psf1.shape[1] assert psf2.shape[0] == psf2.shape[1] psf1 = psf1 / psf1.sum() psf2 = psf2 / psf2.sum() if psf1.shape[0] > psf2.shape[0]: pad = (psf1.shape[0] - psf2.shape[0]) / 2 psf1 = psf1[pad:-pad, pad:-pad] elif psf2.shape[0] > psf1.shape[0]: pad = (psf2.shape[0] - psf1.shape[0]) / 2 psf2 = psf2[pad:-pad, pad:-pad] if method == 'RL': kernel = richardson_lucy(psf2, psf1, iterations=iterations) elif method == 'fft': kernel = create_matching_kernel(psf1, psf2, window=window) # normalize the kernel kernel = kernel / kernel.sum() hdr2 = fits.getheader(psf_sharp) if os.path.exists(kernelname): os.remove(kernelname) fits.append(kernelname, kernel, hdr2) return kernel
def psfmatch_RL(psf_ref, psf_input, kernelname, iterations=30): """ Derive the kernel that matches psf_2match to psf_ref, so that psf_2match, when convolved with the kernel, gives psf_ref. Make sure that both PSF images have the same pixel scales, are centered, and have the same image size. USE THE RICHARDSON-LUCY DECONVOLUTION ALGORITHM. """ psf1 = fits.getdata(psf_ref) psf2 = fits.getdata(psf_input) assert psf1.shape[0] % 2 == 1 assert psf2.shape[0] % 2 == 1 assert psf1.shape[0] == psf1.shape[1] assert psf2.shape[0] == psf2.shape[1] psf1 = psf1 / psf1.sum() psf2 = psf2 / psf2.sum() if psf1.shape[0] > psf2.shape[0]: pad = (psf1.shape[0] - psf2.shape[0]) / 2 psf1 = psf1[pad:-pad, pad:-pad] elif psf2.shape[0] > psf1.shape[0]: pad = (psf2.shape[0] - psf1.shape[0]) / 2 psf2 = psf2[pad:-pad, pad:-pad] kernel = richardson_lucy(psf1, psf2) # normalize the kernel kernel = kernel / kernel.sum() hdr2 = fits.getheader(psf_input) if os.path.exists(kernelname): os.remove(kernelname) fits.append(kernelname, kernel, hdr2) return kernel
def richardson_lucy_deconv(img: np.ndarray, num_iter: int, psf: np.ndarray, clip: bool=False) -> np.ndarray: """ Deconvolves input image with a specified point spread function. This simply calls skimage.restoration.richardson_lucy Parameters ---------- img : np.ndarray Image to filter. num_iter : int Number of iterations to run algorithm psf : Point spread function clip : bool (default = False) If true, pixel value of the result above 1 or under -1 are thresholded for skimage pipeline compatibility. Returns ------- np.ndarray : Deconvolved image, same shape as input """ # TODO ambrosejcarr: the restoration function is producing the following warning: # /usr/local/lib/python3.6/site-packages/skimage/restoration/deconvolution.py:389: RuntimeWarning: invalid value # encountered in true_divide: # relative_blur = image / convolve_method(im_deconv, psf, 'same') img_deconv: np.ndarray = restoration.richardson_lucy(img, psf, iterations=num_iter, clip=clip) # here be dragons. img_deconv is a float. this should not work, but the result looks nice # modulo boundary values? wtf indeed. img_deconv = img_deconv.astype(np.uint16) return img_deconv
def richardson_lucy(img, psf=np.ones((5, 5)) / 25, iterations=30): """ Richardson-Lucy deconvolution """ deconv = restoration.richardson_lucy(img.copy(), psf, iterations=iterations) return deconv
def loop(imgFiles,rank): for f in imgFiles: img = img_as_float(data.load(os.path.join(noisyDir,f))) psf = np.ones((5, 5)) / 25 startTime = time.time() img = richardson_lucy(img, psf, iterations=30) io.imsave(os.path.join(denoisedDir,f), img) print ("Process %d: Took %f seconds for %s" %(rank, time.time() - startTime, f))
def deconvolvePSF(image_path, psf, iterations): img = io.imread(image_path) img = img_as_float(img) img += np.amax(img) * 1E-5 # Restore Image using Richardson-Lucy algorithm deconvolved_RL = restoration.richardson_lucy(img, psf, iterations) # deconvolved_RL = img_as_int(deconvolved_RL) return deconvolved_RL
def deconvolve(self, image, iterations): ## Code for deconvolution psf = ai.airy_psf(self.window, self.psf_radius) image = np.pad(image, int(psf.shape[0] / 2), mode="reflect") deconvolved = restoration.richardson_lucy(image, psf, iterations, False) deconvolved = util.crop(deconvolved, int(psf.shape[0] / 2)) return deconvolved
def processedImage(image, final_size, show=False, save=True): """ Converts image into silhouette with proper size for final cube Input: image name or location of image [String contatining a .jpg/.png/etc] Output: silhouette [2D array] """ # load image, resize, convert to array, and make grayscale img0 = color.rgb2gray( np.asarray(Image.open(image).resize((final_size, final_size)))) # [using method from skimage restoration] # sharpen image after rescaling psf = np.ones((5, 5)) / 25 img0 = conv2(img0, psf, 'same') img_noisy = img0.copy() img_noisy += (np.random.poisson(lam=25, size=img0.shape) - 10) / 255. deconvolved_RL = restoration.richardson_lucy(img_noisy, psf, iterations=30) # [combining skimage functions] # use chan_vese to separate into distinct shades float_deconv = img_as_float(deconvolved_RL) cv = chan_vese(float_deconv, mu=0.25, lambda1=1, lambda2=1, tol=1e-3, max_iter=200, dt=0.5, init_level_set="checkerboard", extended_output=True) # make ~silhouette by taking the hard edge between contrasting colors edge = roberts(cv[0]) # debugging/visual confirmation [toggle-able] if show: plt.plot() plt.gray() plt.imshow(edge) plt.show() if save: if not os.path.exists(imageFolder): os.makedirs(imageFolder) image = os.path.splitext(image)[0] with cd(imageFolder): np.save(image + '_{}'.format(final_size), edge) return edge
def test_richardson_lucy(): psf = np.ones((5, 5)) / 25 data = convolve2d(test_img, psf, "same") np.random.seed(0) data += 0.1 * data.std() * np.random.standard_normal(data.shape) deconvolved = restoration.richardson_lucy(data, psf, 5) path = pjoin(dirname(abspath(__file__)), "camera_rl.npy") np.testing.assert_allclose(deconvolved, np.load(path), rtol=1e-3)
def perform_richardson_lucy_deconv(bandpass_data, bandpass_wvl, LSA_wvl, LSA_data, save_dir, wavelen_val): """ Function to perform the spectral deconvolution of Laser Linewidth from the spectral bandpass data """ #print(LSA_wvl.shape) #print(LSA_data.shape) # print(bandpass_data.shape) for i in range(1000, 1001): #np.shape(bandpass_data)[1]): normalized_data = bandpass_data[:, i] / np.max(bandpass_data[:, i]) wavelength = bandpass_wvl[:, i] bp_data = np.array([wavelength, normalized_data]).T bp_data = bp_data[bp_data[:, 0].argsort()] wavelength = bp_data[:, 0] normalized_data = bp_data[:, 1] #LSA_data = LSA_data[max_loc-480 :max_loc+480] if len(LSA_data) > len(normalized_data): factor = len(LSA_data) / len(normalized_data) wvl_LSA = LSA_wvl[:, i] LSA_data = LSA_data[::int(factor) + 1] wvl_LSA = wvl_LSA[::int(factor) + 1] #LSA_data = LSA_data-0.010 LSA_data = LSA_data / np.max(LSA_data) CW = np.where(LSA_data == max(LSA_data))[0] val = int(25) wvl_LSA = wvl_LSA[int(CW) - val:int(CW) + val] LSA_data = LSA_data[int(CW) - val:int(CW) + val] - 0.01 LSA_data = LSA_data / np.max(LSA_data) # plt.figure(); plt.plot(wvl_LSA, LSA_data,'r') # plt.plot(wavelength, normalized_data,'b.') # plt.grid(True, linestyle=':') # plt.show() normalized_data1 = conv2(normalized_data, LSA_data, mode='same') normalized_data1 = normalized_data1 / np.max(normalized_data1) deconvolved_RL = restoration.richardson_lucy(np.array( [normalized_data]), np.array([LSA_data]), iterations=2) deconvolved_RL = deconvolved_RL.T deconvolved_RL = deconvolved_RL.real print(deconvolved_RL / np.max(deconvolved_RL)) # cc plt.figure() np.savetxt(r"C:\Users\nmishra\Desktop\spectral_deconv\foo.csv", deconvolved_RL, delimiter=",") plt.plot(wavelength, normalized_data, 'b') plt.plot(wavelength, deconvolved_RL, 'r') plt.plot(wvl_LSA, LSA_data, 'go--') plt.show() cc
def _map_function(defl, *args, **kwargs): """ :param defl: :type defl: :param args: :type args: :param kwargs: :type kwargs: :returns: List [inst_freq, amplitude, phase, tfp, shift, pwr_diss] WHERE [type] inst_freq is... [type] amplitude is... [type] phase is... [type] tfp is... [type] shift is... [type] pwr_diss is... """ parm_dict = args[0] pixel_params = args[1] impulse = args[2] pix = Pixel(defl, parm_dict, **pixel_params) if parm_dict['if_only']: inst_freq, _, _ = pix.generate_inst_freq() tfp = 0 shift = 0 amplitude = 0 phase = 0 pwr_diss = 0 elif parm_dict['deconvolve']: iterations = parm_dict['conv_iterations'] impulse = impulse[ parm_dict['impulse_window'][0]:parm_dict['impulse_window'][1]] inst_freq, amplitude, phase = pix.generate_inst_freq() conv = restoration.richardson_lucy(inst_freq, impulse, clip=False, num_iter=iterations) pix.inst_freq = conv pix.find_tfp() tfp = pix.tfp shift = pix.shift pix.calculate_power_dissipation() pwr_diss = pix.power_dissipated else: tfp, shift, inst_freq = pix.analyze() pix.calculate_power_dissipation() amplitude = pix.amplitude phase = pix.phase pwr_diss = pix.power_dissipated return [inst_freq, amplitude, phase, tfp, shift, pwr_diss]
def test_richardson_lucy(): psf = np.ones((5, 5)) / 25 data = convolve2d(test_img, psf, 'same') np.random.seed(0) data += 0.1 * data.std() * np.random.standard_normal(data.shape) deconvolved = restoration.richardson_lucy(data, psf, 5) path = fetch('restoration/tests/camera_rl.npy') np.testing.assert_allclose(deconvolved, np.load(path), rtol=1e-3)
def deconvolve(self): self.load_psf() stk = self.stk.astype('float64') stk = stk - stk.min() stk = stk / stk.max() if self.verbose: iterable = tqdm(range(int(round(self.deconvolution_batches / 2))), desc='Deconvolving Stack') else: iterable = range(int(round(self.deconvolution_batches / 2))) step = int(stk.shape[0] / (self.deconvolution_batches / 2)) if self.gpu: if self.deconvolution_batches > 1: for i in iterable: i0 = int(step * i) for j in iterable: j0 = int(step * j) temp = stk[i0:i0 + step, j0:j0 + step, :] if self.gpu: stk[i0:i0 + step, j0:j0 + step, :] = self.gpu_algorithm.run( fd_data.Acquisition(data=temp, kernel=self.psf), niter=self.deconvolution_niterations).data else: stk[i0:i0 + step, j0:j0 + step, :] = restoration.richardson_lucy( temp, self.psf, self.deconvolution_niterations, clip=False) else: stk = self.gpu_algorithm.run( fd_data.Acquisition(data=stk, kernel=self.psf), niter=self.deconvolution_niterations).data else: stk = restoration.richardson_lucy(stk, self.psf, self.deconvolution_niterations, clip=False) self.stk = stk del self.gpu_algorithm
def rl_dec(array, coupling): kernal = np.zeros((3, 3)) coupling = coupling * .01 kernal[0, 1] = coupling kernal[1, 0] = coupling kernal[1, 2] = coupling kernal[2, 1] = coupling kernal[1, 1] = 1 - 4 * coupling psf = np.asarray(kernal) print psf return restoration.richardson_lucy(array, psf, iterations=30, clip=False)
def rlDeconvolve(img_data, psfFunction, psfParam, psfWidth=16, iterations=30, newWidth=0.5): # skimage.restoration.richardson_lucy accepts float64 as input img_data_64 = convertTo(img_data, np.float64) # Set up PSF xx = np.linspace(-psfWidth, psfWidth, 2 * psfWidth + 1, dtype=np.float32) X, Y = np.meshgrid(xx, xx) pos = np.array([X.ravel(), Y.ravel()]).T psf = psfFunction(pos, 1.0, 0.0, 0.0, psfParam[0], psfParam[1], psfParam[2], psfParam[3], 0.0).reshape(2 * psfWidth + 1, 2 * psfWidth + 1) # PSF for the deconvoluted image psf_new = psfFunction(pos, 1.0, 0.0, 0.0, newWidth * newWidth * psfParam[0], newWidth * newWidth * psfParam[1], newWidth * newWidth * psfParam[2], newWidth * newWidth * psfParam[3], 0.0).reshape(2 * psfWidth + 1, 2 * psfWidth + 1) # The PSF for deconvolution psf_deconv = restoration.richardson_lucy(psf, psf_new, iterations=iterations) # Deconvolve if img_data_64.ndim != 3: img_deconv = restoration.richardson_lucy(img_data_64, psf_deconv, iterations=iterations) else: img_deconv = np.empty(img_data_64.shape) for i in range(img_data_64.shape[-1]): img_deconv[:, :, i] = restoration.richardson_lucy(img_data_64[:, :, i], psf_deconv, iterations=iterations) return img_deconv
def richardsonLucy(): camera = color.rgb2gray(data.camera()) imgO = camera.copy() psf = np.ones((5, 5)) / 25 camera = convolve2d(camera, psf, 'same') camera += 0.5 * camera.std() * np.random.standard_normal(camera.shape) imgN = camera.copy() deconvolved = restoration.richardson_lucy(camera, psf, 5) imgR = deconvolved return [imgO, imgN, imgR]
def deBlur(img): # unused return img ## print "Deblurring" image_gray = img psf = np.ones((3,3)) /9 image_gray = conv2(image_gray, psf, 'same') # Restore Image using Richardson-Lucy algorithm deconvolved_RL = restoration.richardson_lucy(image_gray, psf, iterations=10) return img
def deconvolve(roi): """Deconvolves the image. Args: roi: ROI given as a (z, y, x) subset of image5d. Returns: The ROI deconvolved. """ # currently very simple with a generic point spread function psf = np.ones((5, 5, 5)) / 125 roi_deconvolved = restoration.richardson_lucy(roi, psf, iterations=30) #roi_deconvolved = restoration.unsupervised_wiener(roi, psf) return roi_deconvolved
def test_richardson_lucy_filtered(): test_img_astro = rgb2gray(astronaut()) psf = np.ones((5, 5)) / 25 data = convolve2d(test_img_astro, psf, 'same') deconvolved = restoration.richardson_lucy(data, psf, 5, filter_epsilon=1e-6) path = image_fetcher.fetch('restoration/tests/astronaut_rl.npy') np.testing.assert_allclose(deconvolved, np.load(path), rtol=1e-3, atol=1e-8)
def frame_deconvolution(array, psf, n_it=30): """ Iterative image deconvolution following the scikit-image implementation of the Richardson-Lucy algorithm. Considering an image that has been convolved by the point spread function of an instrument, the algorithm will sharpen the blurred image through a user-defined number of iterations, which changes the regularisation. Reference: William Hadley Richardson, “Bayesian-Based Iterative Method of Image Restoration”, J. Opt. Soc. Am. A 27, 1593-1607 (1972), DOI:10.1364/JOSA.62.000055 See also description at: https://en.wikipedia.org/wiki/Richardson%E2%80%93Lucy_deconvolution Parameters ---------- array : numpy ndarray Input image, 2d frame. psf : numpy ndarray Input psf, 2d frame. n_it : int, optional Number of iterations. Returns ------- deconv : numpy ndarray Deconvolved image. """ if array.ndim != 2: raise TypeError('Input array is not a frame or 2d array.') if psf.ndim != 2: raise TypeError('Input psf is not a frame or 2d array.') max_I = np.amax(array) min_I = np.amin(array) drange = max_I-min_I deconv = richardson_lucy((array-min_I)/drange, psf, iterations=n_it) deconv*=drange deconv+=min_I return deconv
def deconv_RL(f_tpl, w_tpl, bb=4): # Deconvolution of f_tpl using Richardson Lucy algorithm # needed for CRIRES data psf = np.ones((1, bb)) / bb f2 = f_tpl + 0. f_tpl1 = np.reshape(f_tpl, (1, -1)) deconv_RL = restoration.richardson_lucy(f_tpl1 / np.max(f_tpl1) / 2., psf, iterations=30)[0] f_tpl = deconv_RL * np.max(f_tpl1) * 2 rv, ccc = pyasl.crosscorrRV(w_tpl[200:-200], f_tpl[200:-200], w_tpl[200:-200], f2[200:-200], -10., 10., 0.01, skipedge=20) pol = (np.poly1d(np.polyfit(rv, ccc, 15)))(rv) shift = rv[np.argmax(pol)] print('shift RL: ', shift, rv[np.argmax(ccc)]) # there seems to appear a shift in the spectra after the deconvolution # why ??? # correction ??? # more testing needed, or another way of deconvolution plot_RL = 0 if plot_RL: gplot(rv, ccc, 'w l,', rv, pol, 'w l') # gplot(w_tpl, f2, 'w l,', w_tpl /(1+shift/3e5),f_tpl,'w l') pause() # w_tpl /= (1+shift/3e5) ''' bo = 10 f_tpl = f_tpl[bo:-bo] w_tpl = w_tpl[bo:-bo] f_ok = f_ok[bo:-bo] w_ok = w_ok[bo:-bo] x_ok = x_ok[bo:-bo] ''' return f_tpl, w_tpl
def nick(): file_path = 's3://sofroniewn/image-data/smFISH/raw.zarr' raw = da.from_zarr(file_path) blurred = gaussian_filter(raw, (0, 2, 2)) x, y = np.meshgrid(np.linspace(-1, 1, 6), np.linspace(-1, 1, 6)) d = np.sqrt(x * x + y * y) sigma, mu = 2.0, 0.0 psf = np.expand_dims(np.exp(-((d - mu) ** 2 / (2.0 * sigma ** 2))), axis=0) deconvolved = blurred.map_blocks( lambda block: richardson_lucy(block, psf, clip=False) ) viewer = napari.Viewer() viewer.add_image(raw, contrast_limits=(140.0, 1200.0)) viewer.add_image(blurred, contrast_limits=(140.0, 1200.0)) viewer.add_image(deconvolved, contrast_limits=(140.0, 1200.0))
def frame_deblur(raw_frame, sig = 4., Nit = 21, padding = ((10,10), (10,10))): ''' raw_frame: a single frame of image sig: the width of gaussian filter ''' print("Initial size:",raw_frame.shape) psf = build_psf(sig) img = np.pad(raw_frame, padding, mode = 'constant') img = blank_refill(img, cutoff=180, mode = 'peak') dc_image = restoration.richardson_lucy(img, psf, iterations = Nit, clip = False) ci, cf = padding yi, xi = ci yf, xf = cf recrop = dc_image[yi:-yf, xi:-xf] print("Final size:", recrop.shape) return blank_refill(recrop, mode = 'peak')
def loop(imgFiles): for f in imgFiles: img = data.load(os.path.join(originalDir, f)) bwimg = color.rgb2gray(img) # print(type(img)) psf = np.ones((5, 5)) / 25 img = conv2(bwimg, psf, 'same') # Add Noise to Image img = img.copy() img += (np.random.poisson(lam=25, size=img.shape) - 10) / 255. # io.imsave(os.path.join(noisyDir,f), img) scipy.misc.imsave(os.path.join(noisyDir, f), img) startTime = time.time() img = richardson_lucy(img, psf, iterations=30, clip=True) io.imsave(os.path.join(denoisedDir, f), img) print("Took %f seconds for %s" % (time.time() - startTime, f))
def test_richardson_lucy_filtered(dtype_image, dtype_psf): if dtype_image == np.float64: atol = 1e-8 else: atol = 1e-5 test_img_astro = rgb2gray(astronaut()) psf = np.ones((5, 5), dtype=dtype_psf) / 25 data = convolve2d(test_img_astro, psf, 'same') data = data.astype(dtype_image, copy=False) deconvolved = restoration.richardson_lucy(data, psf, 5, filter_epsilon=1e-6) assert deconvolved.dtype == data.dtype path = fetch('restoration/tests/astronaut_rl.npy') np.testing.assert_allclose(deconvolved, np.load(path), rtol=1e-3, atol=atol)
def get_trap_positions(self, frame): self.frame = frame inverted_image = np.max(frame) - frame edgemap = canny(inverted_image, sigma=2.2, low_threshold=self.low_threshold, high_threshold=self.high_threshold) dilated_edges = binary_dilation(edgemap, selem=np.ones_like(frame[:3, :2])) edges = sobel(dilated_edges) deconvolved_image = richardson_lucy(edges, self.kernel, 6, clip=False) self.trap_positions = np.array( peak_local_max(deconvolved_image, threshold_rel=self.point_intensity_limit))
def weiner_filter(img,psf): astro = color.rgb2gray(data.astronaut()) print "running Weiner for a channel" out = np.ndarray(shape=img.shape, dtype=np.float64) # redifine to correct type out = np.copy(img) min_intensity = np.amin(img) out = out - min_intensity max_intensity = np.amax(out) out = out * (1.0 / max_intensity) img = out #psf = np.ones((5, 5)) / 25.0 astro = conv2(astro, psf, 'same') astro += 0.22 * astro.std() * np.random.standard_normal(astro.shape) #deconvolved, _ = restoration.unsupervised_wiener(img, psf) #deconvolved = restoration.wiener(img, psf, 500) deconvolved = restoration.richardson_lucy(img, psf, 200) return deconvolved
img_eq = exposure.equalize_hist(log_img) img_adapteq = exposure.equalize_adapthist(img, clip_limit=0.5,kernel_size=(4,4)) #img_adapteq3 = img - np.min(img) img_adapteq3 = exposure.equalize_adapthist(log_img, clip_limit=0.5,kernel_size=(4,4)) img_adapteq4 = exposure.equalize_adapthist(log_img, clip_limit=0.01,kernel_size=(2,2),nbins=12) #denois_img = img - np.min(img) denois_img = img_adapteq - np.min(img_adapteq) denois_img /= np.max(denois_img) denois_img = np.uint8(denois_img*255) tv_coins = restoration.richardson_lucy(log_img,) better_contrast = exposure.rescale_intensity(denois_img) dst = cv2.fastNlMeansDenoising(better_contrast) dst2 = cv2.fastNlMeansDenoising(denois_img) im_med = median_filter(img, 5) #sift = cv2.Feat .SIFT_create() print hog(img) #print des.shape plt.subplot(131),plt.imshow(real) plt.subplot(132),plt.imshow(tv_coins ) plt.subplot(133),plt.imshow( img_adapteq4)
#%%Reconstruct t2ds.lam=40 t2ds.calibrate() noise=trainingnoise ssdh12= addNoise2D(t2ds.calcSignal(testsmp),noise) srdh12= t2ds.reconstruct(ssdh12) Ddcnv=srdh12 #%% Deconvolve with found convolution Sig = ssdh12 Sig+=Sig.min() esf=Sig.max() #psf=t2ds.sweetSpot sigclip=2*(Sig/esf) Rdcnv = restoration.richardson_lucy(sigclip,psf) Wdcnv=restoration.wiener(sigclip,psf,balance=500,clip=False) #Wdcnv+=1.0 Wdcnv*=esf/2 Rdcnv+=1 Rdcnv*=esf #%%Division in fourier space #Calculate F(testsignal) FS=fft.fft2(Sig) FSlev=np.percentile(np.abs(FS),80) threshFS=np.where(np.abs(FS)<FSlev,0,FS) #Calculate F(sweetspot), (have to pad to correct size for signal) padpsf=np.zeros_like(FS) halfFS=FS.shape[0]/2 halfpsf=iFSS.shape[0]/2
import numpy as np from skimage import color, data, restoration import numpy as np import numpy.random as npr from scipy.signal import convolve2d import helper camera = color.rgb2gray(data.camera()) camera = helper.get_image('cameraman') from scipy.signal import convolve2d psf = np.ones((5, 5)) / 25 camera = convolve2d(camera, psf, 'same') camera += 0.1 * camera.std() * np.random.standard_normal(camera.shape) deconvolved = restoration.richardson_lucy(camera, psf, 5) helper.show_images({'deconv':deconvolved})
def deconv_scikit(d,h): return restoration.richardson_lucy(d, h, 10, clip = False)
import matplotlib.pyplot as plt from scipy.signal import convolve2d as conv2 from skimage import color, data, restoration astro = color.rgb2gray(data.astronaut()) psf = np.ones((5, 5)) / 25 astro = conv2(astro, psf, 'same') # Add Noise to Image astro_noisy = astro.copy() astro_noisy += (np.random.poisson(lam=25, size=astro.shape) - 10) / 255. # Restore Image using Richardson-Lucy algorithm deconvolved_RL = restoration.richardson_lucy(astro_noisy, psf, iterations=30) fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(8, 5)) plt.gray() for a in (ax[0], ax[1], ax[2]): a.axis('off') ax[0].imshow(astro) ax[0].set_title('Original Data') ax[1].imshow(astro_noisy) ax[1].set_title('Noisy data') ax[2].imshow(deconvolved_RL, vmin=astro_noisy.min(), vmax=astro_noisy.max()) ax[2].set_title('Restoration using\nRichardson-Lucy')