def main(): # parse cmd arguments parser = getParser() parser.parse_args() args = getArguments(parser) # prepare logger logger = Logger.getInstance() if args.debug: logger.setLevel(logging.DEBUG) elif args.verbose: logger.setLevel(logging.INFO) # laod input image data_input, header_input = load(args.input) # # check if output image exists # if not args.force: # if os.path.exists(image_gradient_name): # logger.warning('The output image {} already exists. Skipping this step.'.format(image_gradient_name)) # continue # prepare result image data_output = scipy.zeros(data_input.shape, dtype=scipy.float32) # apply the gradient magnitude filter logger.info('Computing the gradient magnitude with Prewitt operator...') generic_gradient_magnitude(data_input, prewitt, output=data_output) # alternative to prewitt is sobel # save resulting mask save(data_output, args.output, header_input, args.force) logger.info('Successfully terminated.')
def main(): # parse cmd arguments parser = getParser() parser.parse_args() args = getArguments(parser) # prepare logger logger = Logger.getInstance() if args.debug: logger.setLevel(logging.DEBUG) elif args.verbose: logger.setLevel(logging.INFO) # laod input image data_input, header_input = load(args.input) # # check if output image exists # if not args.force: # if os.path.exists(image_gradient_name): # logger.warning('The output image {} already exists. Skipping this step.'.format(image_gradient_name)) # continue # prepare result image data_output = scipy.zeros(data_input.shape, dtype=scipy.float32) # apply the gradient magnitude filter logger.info('Computing the gradient magnitude with Prewitt operator...') generic_gradient_magnitude( data_input, prewitt, output=data_output) # alternative to prewitt is sobel # save resulting mask save(data_output, args.output, header_input, args.force) logger.info('Successfully terminated.')
def seam_insert(self, delta, direction, protect=False, start=0): temp_img = np.copy(self.image) for i in range(delta): grey = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY).astype(np.float32) sobel_arr = generic_gradient_magnitude(grey, derivative=sobel) if protect: sobel_arr[self.mask_image > 0] *= self.constant cumulative_map = self.cumulative_map(sobel_arr, 1).astype(np.float32) seam = self.find_seam(cumulative_map) self.seams_index[direction].append(seam) self.delete_seam(seam) self.image = temp_img self.image_width = self.image.shape[1] for i in range(start, start + delta): seam = self.seams_index[direction][i] self.add_seam(seam) if protect: self.add_mask_seam(seam) self.seams_index[direction][i + 1:] = self.update_seams( self.seams_index[direction][i + 1:], seam)
def gradient_filter(im): im_width, im_height = im.size im_arr = numpy.reshape(im.getdata(), (im_height, im_width)) sobel_arr = generic_gradient_magnitude(im, derivative=sobel) gradient = Image.new("L", im.size) gradient.putdata(list(sobel_arr.flat)) return gradient
def get_removal_seams(self): temp_img = self.image direction = 0 if self.object_height > self.object_width: self.rotate_image(2) self.rotate_mask_image(2) direction = 1 while len(np.where(self.mask_image > 0)[0]) > 0: grey = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY).astype(np.float32) sobel_arr = generic_gradient_magnitude(grey, derivative=sobel) sobel_arr[self.mask_image > 0] *= -self.constant cumulative_map = self.cumulative_map(sobel_arr, 0) seam = self.find_seam(cumulative_map) self.seams_index[direction].append(seam) self.delete_seam(seam) self.delete_mask_seam(seam) self.delta = len(self.seams_index[direction]) self.original_delta = self.delta self.seam_insert(self.delta, direction, start=self.delta) self.image = temp_img self.image_height, self.image_width = self.image.shape[:2] if direction == 1: self.rotate_mask_image(2) self.original_seams[0] = self.seams_index[0].copy() self.original_seams[1] = self.seams_index[1].copy()
def sobelFilter (im): im = im.convert("F") width, height = im.size im_arr = np.reshape( im.getdata( ), (height, width) ) sobel_arr = generic_gradient_magnitude( im, derivative=sobel ) gradient = Image.new("F", im.size) gradient.putdata( list( sobel_arr.flat ) ) return gradient
def gradient_filter(im): """ Takes a grayscale img and retuns the Sobel operator on the image. Fast thanks to Scipy/Numpy. See slow_gradient_filter for an implementation of what the Sobel operator is doing @im: a grayscale image represented in floats """ print_fn("Computing energy function using the Sobel operator") im_width, im_height = im.size im_arr = numpy.reshape(im.getdata(), (im_height, im_width)) sobel_arr = generic_gradient_magnitude(im, derivative=sobel) gradient = Image.new("F", im.size) gradient.putdata(list(sobel_arr.flat)) return gradient
def seam_remove(self, delta, direction, protect=False): for i in range(delta): grey = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY).astype(np.float32) sobel_arr = generic_gradient_magnitude(grey, derivative=sobel) if protect: sobel_arr[self.mask_image > 0] *= self.constant cumulative_map = self.cumulative_map(sobel_arr, 0) seam = self.find_seam(cumulative_map) self.seams_index[direction].append(seam) self.delete_seam(seam) if protect: self.delete_mask_seam(seam)
def _calculate_focus_measure(self, src, operator, roi): ''' see IMPLEMENTATION OF A PASSIVE AUTOMATIC FOCUSING ALGORITHM FOR DIGITAL STILL CAMERA DOI 10.1109/30.468047 and http://cybertron.cg.tu-berlin.de/pdci10/frankencam/#autofocus ''' # need to resize to 640,480. this is the space the roi is in # s = resize(grayspace(pychron), 640, 480) src = grayspace(src) v = crop(src, *roi) di = dict(var=lambda x:variance(x), laplace=lambda x: get_focus_measure(x, 'laplace'), sobel=lambda x: ndsum(generic_gradient_magnitude(x, sobel, mode='nearest')) ) func = di[operator] return func(v)
def _calculate_focus_measure(self, src, operator, roi): ''' see IMPLEMENTATION OF A PASSIVE AUTOMATIC FOCUSING ALGORITHM FOR DIGITAL STILL CAMERA DOI 10.1109/30.468047 and http://cybertron.cg.tu-berlin.de/pdci10/frankencam/#autofocus ''' # need to resize to 640,480. this is the space the roi is in # s = resize(grayspace(pychron), 640, 480) src = grayspace(src) v = crop(src, *roi) di = dict(var=lambda x: variance(x), laplace=lambda x: get_focus_measure(x, 'laplace'), sobel=lambda x: ndsum( generic_gradient_magnitude(x, sobel, mode='nearest'))) func = di[operator] return func(v)
def EdgeMapExtraction(im, **kwargs): """Function to apply different filters to obtain maps based on edge detection Parameters ---------- im: ndarray 2D or 3D Input image. edge_detector: str Selection of the edge detector wanted: ['Sobel1stDev', 'Prewitt1stDev', 'Sobel2ndDev', 'Prewitt2ndDev', 'GaborBank', 'PhaseCong']. Returns ------- maps: ndarray of np.double If edge_detector is either 'Sobel1stDev', 'Prewitt1stDev', 'Sobel2ndDev', 'Prewitt2ndDev', maps is of size of im. If edge_detector is 'GaborBank', the size depends of the configuration of the filter bank. If edge_detector is 'PhaseCong', two maps of the same size as im are returned. The first map is an edge-based detection whereas the second map is a blob-based detector. """ # Check the dimension of the input image if len(im.shape) == 2: nd_im = 2 elif len(im.shape) == 3: nd_im = 3 else: raise ValueError('mahotas.edge: Can only handle 2D and 3D images.') # Assign the edge detector edge_detector= kwargs.pop('edge_detector', 'Sobel1stDev') detector_list = ['Sobel1stDev', 'Prewitt1stDev', 'Sobel2ndDev', 'Prewitt2ndDev', 'GaborBank', 'PhaseCong'] if not any(edge_detector in dl for dl in detector_list): raise ValueError('mahotas.edge: The name of the detector is unknown.') if edge_detector == 'Sobel1stDev': edge_im = generic_gradient_magnitude(im, sobel) elif edge_detector == 'Prewitt1stDev': edge_im = generic_gradient_magnitude(im, prewitt) elif edge_detector == 'Sobel2ndDev': edge_im = generic_laplace(im, sobel) elif edge_detector == 'Prewitt2ndDev': edge_im = generic_laplace(im, prewitt) elif edge_detector == 'GaborBank': # Check that the input image is only 2D if nd_im != 2: raise ValueError('mahotas.edge.phase-congruency: Cannot handle 3D image yet. Go for 2D.') # Extract the value of the parameters n_freq = kwargs.pop('n_freq', 10) freq_range = kwargs.pop('freq_range', (.05, .2)) n_theta = kwargs.pop('n_theta', 6) win_size = kwargs.pop('win_size', (15., 15.)) # Generate the different kernel which are needed kernels_gabor, kernels_gabor_params = GaborKernelBank(n_freq=n_freq, freq_range=freq_range, n_theta=n_theta, win_size=win_size) # Extract the maps from Gabor edge_im = BuildMaps2DGabor(im, kernels_gabor) # Return the maps and the parameters of the Gabor kernels return (edge_im, kernels_gabor_params) elif edge_detector == 'PhaseCong': # Check that the input image is only 2D if nd_im != 2: raise ValueError('mahotas.edge.phase-congruency: Cannot handle 3D image yet. Go for 2D.') # Extract the value of the parameters nscale = kwargs.pop('nscale', 5) norient = kwargs.pop('norient', 6) minWaveLength = kwargs.pop('minWaveLength', 3) mult = kwargs.pop('mult', 2.1) sigmaOnf = kwargs.pop('sigmaOnf', .55) k = kwargs.pop('k', 2.) cutOff = kwargs.pop('cutOff', .5) g = kwargs.pop('g', 10) noiseMethod = kwargs.pop('noiseMethod', -1) M, m, ori, ft, PC, EO, T = phc.phasecong(im, nscale=nscale, norient=norient, minWaveLength=minWaveLength, mult=mult, sigmaOnf=sigmaOnf, k=k, cutOff=cutOff, g=g, noiseMethod=noiseMethod) return [M, m] return edge_im
def _calculate_full_energy(self): return generic_gradient_magnitude(self.get_image_matrix(), derivative = sobel)
def fit(self, modality, ground_truth=None, cat=None): """Compute the images images. Parameters ---------- modality : object of type TemporalModality The modality object of interest. ground-truth : object of type GTModality or None The ground-truth of GTModality. If None, the whole data will be considered. cat : str or None String corresponding at the ground-truth of interest. Cannot be None if ground-truth is not None. Return ------ self : object Return self. """ super(EdgeSignalExtraction, self).fit(modality=modality, ground_truth=ground_truth, cat=cat) # Check that the filter provided is known if self.edge_detector not in FILTER: raise ValueError('{} filter is unknown'.format(self.edge_detector)) self.data_ = [] # SOBEL filter if self.edge_detector == 'sobel': # Compute the gradient in the three direction Y, X, Z grad_y = sobel(modality.data_, axis=0) grad_x = sobel(modality.data_, axis=1) grad_z = sobel(modality.data_, axis=2) # Compute the magnitude gradient self.data_.append(generic_gradient_magnitude(modality.data_, sobel)) # Compute the gradient azimuth self.data_.append(np.arctan2(grad_y, grad_x)) # Compute the gradient elevation self.data_.append(np.arccos(grad_z / self.data_[0])) # PREWITT filter elif self.edge_detector == 'prewitt': # Compute the gradient in the three direction Y, X, Z grad_y = prewitt(modality.data_, axis=0) grad_x = prewitt(modality.data_, axis=1) grad_z = prewitt(modality.data_, axis=2) # Compute the magnitude gradient self.data_.append(generic_gradient_magnitude(modality.data_, prewitt)) # Compute the gradient azimuth self.data_.append(np.arctan2(grad_y, grad_x)) # Compute the gradient elevation self.data_.append(np.arccos(grad_z / self.data_[0])) # SCHARR filter elif self.edge_detector == 'scharr': # Compute the gradient in the three direction Y, X, Z grad_y = scharr(modality.data_, axis=0) grad_x = scharr(modality.data_, axis=1) grad_z = scharr(modality.data_, axis=2) # Compute the magnitude gradient self.data_.append(generic_gradient_magnitude(modality.data_, scharr)) # Compute the gradient azimuth self.data_.append(np.arctan2(grad_y, grad_x)) # Compute the gradient elevation self.data_.append(np.arccos(grad_z / self.data_[0])) # KIRSCH filter elif self.edge_detector == 'kirsch': conv_data = np.zeros((modality.data_.shape[0], modality.data_.shape[1], modality.data_.shape[2], len(KIRSCH_FILTERS))) # Compute the convolution for each slice for sl in range(modality.data_.shape[2]): for idx_kirsch, kirsh_f in enumerate(KIRSCH_FILTERS): conv_data[:, :, sl, idx_kirsch] = convolve( modality.data_[:, :, sl], kirsh_f, mode='reflect') # Extract the maximum gradients self.data_.append(np.ndarray.max(conv_data, axis=3)) # Extract the orientattion of the gradients self.data_.append(KIRSCH_DIRECTIONS[np.ndarray.argmax(conv_data, axis=3)]) # LAPLACIAN filter elif self.edge_detector == 'laplacian': self.data_.append(laplace(modality.data_)) # Convert the data into a numpy array self.data_ = np.array(self.data_) # Replace the few NaN value to zero self.data_ = np.nan_to_num(self.data_) return self
def edge_detection(self): return generic_gradient_magnitude(self.image, sobel)
def Sobel(image): sobel_arr = generic_gradient_magnitude(image, derivative=sobel) gradient = Image.new("I", image.size) gradient.putdata(list(sobel_arr.flat)) return gradient
def _calculate_full_energy(self): return generic_gradient_magnitude(self.get_image_matrix(), derivative=sobel)