def first_prewitt(im): prewit_x = np.zeros(im.shape) filters.prewitt(im, 1, prewit_x) prewit_y = np.zeros(im.shape) filters.prewitt(im, 0, prewit_y) prewitt = np.sqrt(prewit_x*prewit_x + prewit_y*prewit_y) return prewitt
def gradient(image, type=0): if type == 0: Ix = filters.sobel(image, axis=1) Iy = filters.sobel(image, axis=0) return Ix, Iy else: Ix = filters.prewitt(image, axis=1) Iy = filters.prewitt(image, axis=0) return Ix, Iy
def apply_prewitt(img): imx = zeros(img.shape) filters.prewitt(img,1,imx) imy = zeros(img.shape) filters.prewitt(img,0,imy) #the magnitude grad = sqrt(imx**2+imy**2) return imx,imy,grad
def apply_prewitt(img): imx = zeros(img.shape) filters.prewitt(img, 1, imx) imy = zeros(img.shape) filters.prewitt(img, 0, imy) #the magnitude grad = sqrt(imx**2 + imy**2) return imx, imy, grad
def apply_prewitt(img): img = img.copy() im_x = np.zeros(img.shape) filters.prewitt(img, 1, im_x, mode="nearest") im_y = np.zeros(img.shape) filters.prewitt(img, 0, im_y, mode="nearest") #the magnitude grad = np.sqrt(im_x**2 + im_y**2) return im_x, im_y, grad
def generateDetector(image, edgeDetector, custom=0, only_x=1): if edgeDetector == 'prewitt': dx = filters.prewitt(image, 0) # horizontal derivative dy = filters.prewitt(image, 1) # vertical derivative mag = np.hypot(dx.astype('int32'), dy.astype('int32')) # magnitude mag *= 255.0 / np.max(mag) # normalize (Q&D) return mag elif edgeDetector == "sobel": if custom == 1: return sobel_filter(image) else: dx = filters.sobel(image, 0) # horizontal derivative dy = filters.sobel(image, 1) # vertical derivative mag = np.hypot(dx.astype('int32'), dy.astype('int32')) # magnitude mag *= 255.0 / np.max(mag) # normalize (Q&D) if only_x == 1: return dx return mag elif edgeDetector == "log": if custom == 0: print( "No in-built function available for log edge filter. Construct custom filter laplacian_of_gaussian and call generateDetector(image,'log',1)" ) return filters.gaussian_laplace(image, 0.01, output=None, mode='reflect', cval=0.0) else: return laplcian_of_gaussian(image) elif edgeDetector == "roberts": if custom == 0: return roberts(image) if custom == 1: return roberts_filter(image) elif edgeDetector == "canny": # image = image.astype(np.uint8) from scipy import ndimage, misc misc.imsave('fileName.jpg', image) image = ndimage.imread('fileName.jpg', 0) return cv2.Canny(np.uint8(image), 250, 255, 3) #,L2gradient=False) # return feature.canny(np.uint8(image), sigma = 100) else: # lower threshold- 25, upper threshold- 255 return cv2.Canny(image, 25, 255)
def magiceye_solver(x): """ Solves the autostereogram image represented by the ndarray, x """ shape = x.shape if len(shape) >= 3: m, n, c = shape color_image = True else: m, n, c = shape[0], shape[1], 1 color_image = False solution = np.zeros((m, c * n), dtype=float) for i in range(c): if color_image: color = x[:, :, i] else: color = x if color.std() == 0.0: continue shifted = shift_pic(color) filt_1 = filters.prewitt(shifted) filt_2 = filters.uniform_filter(filt_1, size=(5, 5)) if ski_filter: filt_2 = post_process(filt_2) m, n = filt_2.shape solution[:m, i * n:i * n + n] = filt_2 return solution[:, :c * n]
def question1(img): im = array(Image.open(img).convert('L')) Image.fromarray(im).save(img + '_gray.png') # Sobel start_time = timer() imx_sobel = zeros(im.shape) filters.sobel(im, 1, imx_sobel) imy_sobel = zeros(im.shape) filters.sobel(im, 0, imy_sobel) magnitude_sobel = sqrt(imx_sobel**2+imy_sobel**2) end_time = timer() print('[Sobel] Duration: ' + str(end_time - start_time)) # Save sobel images Image.fromarray(imx_sobel).convert('RGB').save(img + '_sobel_x.png') Image.fromarray(imy_sobel).convert('RGB').save(img + '_sobel_y.png') Image.fromarray(magnitude_sobel).convert('RGB').save(img + '_sobel_magnitude.png') # Prewitt start_time = timer() imx_prewitt = zeros(im.shape) filters.prewitt(im, 1, imx_prewitt) imy_prewitt = zeros(im.shape) filters.prewitt(im, 0, imy_prewitt) magnitude_prewitt = sqrt(imx_prewitt**2+imy_prewitt**2) end_time = timer() print('[Prewitt] Duration: ' + str(end_time - start_time)) Image.fromarray(imy_prewitt).convert('RGB').save(img + '_prewitt_y.png') Image.fromarray(imx_prewitt).convert('RGB').save(img + '_prewitt_x.png') Image.fromarray(magnitude_prewitt).convert('RGB').save(img + '_prewitt_magnitude.png')
def boundary_penalties_array(self, axis, sigma=None): import scipy.ndimage.filters as scf # for axis in range(0,dim): filtered = scf.prewitt(self.img, axis=axis) if sigma is None: sigma2 = np.var(self.img) else: sigma2 = sigma ** 2 filtered = np.exp(-np.power(filtered, 2) / (256 * sigma2)) # srovnán hodnot tak, aby to vycházelo mezi 0 a 100 # cc = 10 # filtered = ((filtered - 1)*cc) + 10 logger.debug( 'ax %.1g max %.3g min %.3g avg %.3g' % ( axis, np.max(filtered), np.min(filtered), np.mean(filtered)) ) # # @TODO Check why forumla with exp is not stable # Oproti Boykov2001b tady nedělím dvojkou. Ta je tam jen proto, # aby to slušně vycházelo, takže jsem si jí upravil # Originální vzorec je # Bpq = exp( - (Ip - Iq)^2 / (2 * \sigma^2) ) * 1 / dist(p,q) # filtered = (-np.power(filtered,2)/(16*sigma)) # Přičítám tu 256 což je empiricky zjištěná hodnota - aby to dobře vyšlo # nedávám to do exponenciely, protože je to numericky nestabilní # filtered = filtered + 255 # - np.min(filtered2) + 1e-30 # Ještě by tady měl a následovat exponenciela, ale s ní je to numericky # nestabilní. Netuším proč. # if dim >= 1: # odecitame od sebe tentyz obrazek # df0 = self.img[:-1,:] - self.img[] # diffs.insert(0, return filtered
def prewitt(self, *args, **kw): '''see scipy.ndimage.filters.prewitt''' return Image(_filters.prewitt(self, *args, **kw)).convert_type(self.dtype)
def prewitt(im, axis, im2): filters.prewitt(im, axis, im2)
def prewitt_filter(grid,axis): filtered = grid.copy() scifilt.prewitt(grid,axis,filtered, mode='nearest') return filtered
I = sqrt(ix**2 + iy**2) subplot(144) title('I') imshow(I) figure("Prewitt Filter") gray() subplot(141) title('Original') imshow(im) subplot(142) title('Ix') ix = zeros(im.shape) filters.prewitt(im,1,ix) #1 means x imshow(ix) subplot(143) title('Iy') iy = zeros(im.shape) filters.prewitt(im,0,iy) #0 means y imshow(iy) I = sqrt(ix**2 + iy**2) subplot(144) title('I') imshow(I) show()
from numpy import * from pylab import * from scipy.ndimage import filters fname = "C:\\skunkworx\\Area52\\home\\6008895\dev\\bitbucket\\me-ml\\computervision\\jesolem-PCV-790b64d\\data\\empire.jpg" im = array(Image.open(fname).convert("L")) figure() subplot(1, 4, 1) xlabel("orig. grayscale") imshow(im) imx = zeros(im.shape) filters.prewitt(im, 1, imx) subplot(1, 4, 2) xlabel("x-derivative") imshow(imx) imy = zeros(im.shape) filters.prewitt(im, 0, imy) subplot(1, 4, 3) xlabel("y-derivative") imshow(imy) magnitude = sqrt(imx**2 + imy**2) subplot(1, 4, 4) xlabel("gradient magnitude") imshow(magnitude)
from matplotlib import pyplot from matplotlib.pyplot import * from numpy import * from scipy.ndimage import filters from scipy.signal import convolve2d from gradMagnitude import get #bring image, make grayscale im = array(Image.open('empire.jpg').convert('L')) gray() imshow(im) #create new image with Prewitt-filtered original image imPrewitt = zeros(im.shape) filters.prewitt(im, 1, imPrewitt) imPrewittMagnitude = get(imPrewitt) pyplot.figure("Prewitt Gradient Magnitude") imshow(imPrewittMagnitude) #create new image with Sobel-filtered original image imSobel = zeros(im.shape) filters.sobel(im, 1, imSobel) imSobelMagnitude = get(imSobel) figure('Sobel Gradient Magnitude') imshow(imSobelMagnitude) #create new images wirh [-1,1] and [-1,1]T filters filt = np.array([-1, 0]) xArr, yArr = np.gradient(np.array(im, dtype=np.float)) for x in range(1, len(im) - 1):
def compute_sensitive(image, weight_type='none'): weight = torch.ones_like(image) n, c, h, w = image.shape #1,3,299,299 if weight_type == 'none': return weight else: if weight_type == 'gradient': from scipy.ndimage import filters im = image.cpu().numpy().squeeze(axis=0).transpose( (1, 2, 0)) #229,229,3 im_Prewitt_x = np.zeros(im.shape, dtype='float32') im_Prewitt_y = np.zeros(im.shape, dtype='float32') im_Prewitt_xy = np.zeros(im.shape, dtype='float32') filters.prewitt(im, 1, im_Prewitt_x) filters.prewitt(im, 0, im_Prewitt_y) im_Prewitt_xy = np.sqrt(im_Prewitt_x**2 + im_Prewitt_y**2) im_Prewitt_xy = im_Prewitt_xy.transpose( (2, 0, 1))[np.newaxis, ...] #1,3,299,299 weight = torch.from_numpy(im_Prewitt_xy).cuda().float() else: for i in range(h): for j in range(w): left = max(j - 1, 0) right = min(j + 2, w) up = max(i - 1, 0) down = min(i + 2, h) for k in range(c): if weight_type == 'variance': weight[0, k, i, j] = torch.std(image[0, k, up:down, left:right]) elif weight_type == 'variance_mean': weight[0, k, i, j] = torch.std( image[0, k, up:down, left:right]) * torch.mean( image[0, k, up:down, left:right]) elif weight_type == 'contrast': weight[0, k, i, j] = ( torch.max(image[0, k, up:down, left:right]) - torch.min(image[0, k, up:down, left:right]) ) / (torch.max(image[0, k, up:down, left:right]) + torch.min(image[0, k, up:down, left:right])) elif weight_type == 'contrast_mean': contrast = ( torch.max(image[0, k, up:down, left:right]) - torch.min(image[0, k, up:down, left:right]) ) / (torch.max(image[0, k, up:down, left:right]) + torch.min(image[0, k, up:down, left:right])) weight[0, k, i, j] = contrast * torch.mean( image[0, k, up:down, left:right]) if torch.isnan(weight[0, k, i, j]): weight[0, k, i, j] = 1e-4 weight = 1.0 / (weight + 1e-4) for k in range(c): weight[0, k, :, :] = (weight[0, k, :, :] - torch.min( weight[0, k, :, :])) / (torch.max(weight[0, k, :, :]) - torch.min(weight[0, k, :, :])) return weight
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 outline(path='../../images/squares.jpg'): print "RUNNING" im = array(Image.open(path).convert('L')) #Sodel derivative filters imx = zeros(im.shape) filters.sobel(im, 1, imx) imy = zeros(im.shape) filters.sobel(im, 0, imy) magnitude = sqrt(imx**2 + imy**2) alpha = arctan2(imy, imx) g_im = concatenate([imx * cos(alpha), imy * sin(alpha)]) print "\n SOBEL" plt.figure("Sobel", figsize=(13, 5)) print "The Original Image" plt.subplot(1, 6, 1) plt.imshow(im, cmap=cm.Greys_r) plt.xlabel("Original Image") print "The X-Derivative (Sobel)" plt.subplot(1, 6, 2) plt.imshow(imx, cmap=cm.Greys_r) plt.xlabel("X-Derivative") print "The Y-Derivative (Sobel)" plt.subplot(1, 6, 3) plt.imshow(imy, cmap=cm.Greys_r) plt.xlabel("Y-Derivative") print "The Magnitude" plt.subplot(1, 6, 4) plt.imshow(magnitude, cmap=cm.Greys_r) plt.xlabel("Gradient Magnitude") print "The Direction" plt.subplot(1, 6, 5) plt.imshow(alpha, cmap=cm.Greys_r) plt.xlabel("Gradient Direction") print "The Gradient Matrix" plt.subplot(1, 6, 6) plt.imshow(g_im, cmap=cm.Greys_r) plt.show() imx = zeros(im.shape) filters.prewitt(im, 1, imx) imy = zeros(im.shape) filters.prewitt(im, 0, imy) magnitude = sqrt(imx**2 + imy**2) alpha = arctan2(imy, imx) g_im = concatenate([imx * cos(alpha), imy * sin(alpha)]) print "\n PREWITT" plt.figure("Prewitt", figsize=(13, 5)) print "The Original Image" plt.subplot(1, 6, 1) plt.imshow(im, cmap=cm.Greys_r) plt.xlabel("Original Image") print "The X-Derivative (Sobel)" plt.subplot(1, 6, 2) plt.imshow(imx, cmap=cm.Greys_r) plt.xlabel("X-Derivative") print "The Y-Derivative (Sobel)" plt.subplot(1, 6, 3) plt.imshow(imy, cmap=cm.Greys_r) plt.xlabel("Y-Derivative") print "The Magnitude" plt.subplot(1, 6, 4) plt.imshow(magnitude, cmap=cm.Greys_r) plt.xlabel("Gradient Magnitude") print "The Direction" plt.subplot(1, 6, 5) plt.imshow(alpha, cmap=cm.Greys_r) plt.xlabel("Gradient Direction") print "The Gradient Matrix" plt.subplot(1, 6, 6) plt.imshow(g_im, cmap=cm.Greys_r) plt.show() print "Done"