def setUp(self): ref_image = ascent() center = np.array((256, 256)) shifts = np.array( [ (0.0, 0.0), (4.3, 2.13), (1.65, 3.58), (-2.3, 2.9), (5.2, -2.1), (2.7, 2.9), (5.0, 6.8), (-9.1, -9.5), (-9.0, -9.9), (-6.3, -9.2), ] ) s = hs.signals.Signal2D(np.zeros((10, 100, 100))) for i in range(10): # Apply each sup-pixel shift using FFT and InverseFFT offset_image = fourier_shift(np.fft.fftn(ref_image), shifts[i]) offset_image = np.fft.ifftn(offset_image).real # Crop central regions of shifted images to avoid wrap around s.data[i, ...] = offset_image[center[0] : center[0] + 100, center[1] : center[1] + 100] self.signal = s self.shifts = shifts
def demo(): bin_edges = 0, 55, 200, 255 quantiles = 0, 0.2, 0.5, 1.0 img = ascent() normed = hist_norm(img, bin_edges, quantiles) x1, y1 = ecdf(img.ravel()) x2, y2 = ecdf(normed.ravel()) fig = plt.figure() gs = plt.GridSpec(2, 2) ax1 = fig.add_subplot(gs[0, 0]) ax2 = fig.add_subplot(gs[0, 1], sharex=ax1, sharey=ax1) ax3 = fig.add_subplot(gs[1, :]) for aa in (ax1, ax2): aa.set_axis_off() ax1.imshow(img, cmap=plt.cm.gray) ax1.set_title('Original') ax2.imshow(normed, cmap=plt.cm.gray) ax2.set_title('Normalised') ax3.plot(x1, y1 * 100, lw=2, label='Original') ax3.plot(x2, y2 * 100, lw=2, label='Normalised') for xx in bin_edges: ax3.axvline(xx, ls='--', c='k') for yy in quantiles: ax3.axhline(yy * 100., ls='--', c='k') ax3.set_xlim(bin_edges[0], bin_edges[-1]) ax3.set_xlabel('Pixel value') ax3.set_ylabel('Cumulative %') ax3.legend(loc=2) plt.show()
def 二维图像卷积(): image = misc.ascent() # 二维图像数组,ascent 图像 w = np.zeros((50, 50)) # 全 0 二维数组,卷积核 w[0][0] = 1.0 # 修改参数,调整滤波器 w[49][25] = 1.0 global image_new image_new = signal.fftconvolve(image, w) # 使用 FFT 算法进行卷积
def main(): # ---- Init data ---------- img = misc.ascent() U, S, VT = svd(img, full_matrices=False) # ------------------------- # -------- 1st Plot -------- k_x_axis = [] y1_forb_dist = [] y2_comp_ratio = [] for k in range(len(img)): k_x_axis.append(k) rec_img, y1, y2 = get_rec_forb_comp(img, U, copy.deepcopy(S), VT, k) y1_forb_dist.append(y1) y2_comp_ratio.append(y2) utils.plot_graph(k_x_axis, "k", y1_forb_dist, "Forb Dist") utils.plot_graph(k_x_axis, "k", y2_comp_ratio, "Compression Ratio") # ------------------------- # -------- 2nd Plot -------- k_image_list = [5, 20, 45, 250, 511] image_list = [] y1_forb_dist = [] y2_comp_ratio = [] for k in k_image_list: rec_img, y1, y2 = get_rec_forb_comp(img, U, copy.deepcopy(S), VT, k) image_list.append(rec_img) y1_forb_dist.append(y1) y2_comp_ratio.append(y2) utils.plot_images_from_list(image_list, k_image_list, y1_forb_dist, y2_comp_ratio)
def test_blur(): orig = misc.ascent() blurred = blur(orig) final = blur(blurred) for i in range(5): final = blur(final) show(orig, blurred, final)
def main(): k_arr = {10: 0, 30: 0, 50: 0, 80: 0, 300: 0, 512: 0} img = misc.ascent() compression_obj = img_compression(img) flag = False index = [i for i in range(img.shape[0])] ratio_lst = list() dist_lst = list() for k in range(img.shape[0]): if k in k_arr: flag = True compression_obj.do_compression(k, flag) ratio = compression_obj.compression_ratio() dist = compression_obj.dist_to_origin() ratio_lst.append(ratio) dist_lst.append(dist) print("k:" + str(k) + ", compression ratio:" + str(ratio) + ", Frobenius distance to origin: " + str(dist)) flag = False plt.figure(1) plt.plot(index, ratio_lst) plt.xlabel("Matrix Rank") plt.ylabel("Compression Ratio") plt.title("Compression Ratio") plt.show() plt.figure(2) plt.plot(index, dist_lst) plt.xlabel("Matrix Rank") plt.ylabel("% Frobenius Distance") plt.title("Frobenius Distance") plt.show()
def test_gradient(): orig = misc.ascent() grad = gradient_grey(orig) grad_one = grad.copy() for i in range(5): grad = gradient_grey(grad) show(orig, grad_one, grad)
def test_denoising(): from numpy.random import poisson from scipy.misc import ascent # load test image x0 = ascent().astype(np.float) x0 /= x0.max() # apply Poisson noise x0 = poisson(1000*x0) # compute approximation and detail coefficients ajs2, djs2 = msvst.msvst(x0) # compute level-dependent standard deviation for Normal distribution sigma2s = msvst.sigma2s(len(ajs2)) # false positive rate parameter used in denoising fpr = 5e-3 dt = list() for i in range(len(djs2) - 1): # apply hypothesis testing to each detail coefficient d = msvst.H1(djs2[i], sigma2s[i], fpr) dt.append(d) plt.subplot(1, 2, 1) plt.imshow(x0) plt.title('original') plt.subplot(1, 2, 2) des = ajs2[-1] + np.stack(dt, axis=0).sum(axis=0) des = msvst.imsvst(ajs2, dt) plt.imshow(des) plt.title('denoised') plt.show()
def example_plot_image_ascent(): from scipy.misc import ascent ascent = np.rot90(ascent(), -1) plot_image(ascent, np.arange(0, ascent.shape[0]), np.arange(0, ascent.shape[1]), cmap='gray')
def test_gs_2d_float(self, sigma): """Test the Gaussian smoother in 2d.""" a = misc.ascent() a = a + 0.1 sp_smoothed = gaussian_filter(a, sigma=sigma) dv_smoothed = gaussian_smooth(a, sigma=sigma) assert np.amax(np.abs(sp_smoothed - np.array(dv_smoothed))) <= 1e-5
def __init__(self): self.data = ascent().astype("float32") self.data1d = self.data[:, 0] # non-contiguous data self.data3d = np.tile(self.data[:128, :128], (128, 1, 1)) self.data_refs = { 1: self.data1d, 2: self.data, 3: self.data3d, }
def process_image_01(): img = misc.ascent() plt.gray() plt.axis('off') # removes the axis and the ticks plt.imshow(img) print(img.dtype) print(img.shape) plt.show()
def get_test_image(WIDTH, color=False): if not color: I = cv2.resize(ascent().astype(np.float32), (WIDTH, WIDTH)) else: I = cv2.resize( face(gray=False)[:, :768].astype(np.float32), (WIDTH, WIDTH)) I /= 255. return np.asfortranarray(I, dtype=np.float32)
def test_grad_blur(): orig = misc.ascent() blurred = blur(gradient_grey(orig)) final = blur(gradient_grey(blurred)) for i in range(4): final = blur(gradient_grey(final)) final = three_channel_grey(final) final = F.adjust_brightness(final, 2.0) final = to_grey(final) show(orig, blurred, final)
def change_image(self, combobox): src = self.combobox.get_active_text() if src == "face": self.img = misc.face() elif src == "ascent": self.img = misc.ascent() self.draw_image() self.node_socket_output.write(pickle.dumps(self.img))
def test_2d_tv_denoise(): rng = np.random.RandomState(123) data = ascent().astype(float) data_noisy = data + data.std() * rng.randn(*data.shape) data_clean = tv_denoise(data, weight=60) norm_noisy = np.linalg.norm(data - data_noisy) / np.linalg.norm(data) norm_clean = np.linalg.norm(data - data_clean) / np.linalg.norm(data) np.testing.assert_allclose(norm_noisy, 0.48604971) np.testing.assert_allclose(norm_clean, 0.10888393)
def test_gs_2d_int(self, sigma): """Test the Gaussian smoother in 2d.""" a = misc.ascent() sp_smoothed = gaussian_filter(a, sigma=sigma) dv_smoothed = gaussian_smooth(a, sigma=sigma) try: s = max(sigma) except TypeError: s = sigma assert np.amax(np.abs(sp_smoothed - np.array(dv_smoothed))) <= s
def test_convolve2d_1(self, xp, scp): # see cupy/cupy#5989 from scipy import misc ascent = misc.ascent() if xp is cupy: ascent = xp.asarray(ascent) scharr = xp.array([[-3 - 3j, 0 - 10j, +3 - 3j], [-10 + 0j, 0 + 0j, +10 + 0j], [-3 + 3j, 0 + 10j, +3 + 3j]]) # Gx + j*Gy return scp.signal.convolve2d(ascent, scharr, boundary='symm', mode='same')
def test_2d(fac=.3): from scipy.misc import ascent d = ascent().astype(np.float32) d = d[:, :-10] sig = .2 * np.amax(d) y = d + sig * np.random.uniform(0, 1., d.shape) out = nlm2(y.astype(np.float32), fac * sig, 3, 5) return y, out
def test_2d(fac = .3): from scipy.misc import ascent d = ascent().astype(np.float32) d = d[:,:-10] sig = .2*np.amax(d) y = d+sig*np.random.uniform(0,1.,d.shape) out = nlm2(y.astype(np.float32),fac*sig,3,5) return y, out
def setUpClass(cls): cls.image = np.ascontiguousarray(ascent()[:, :511], dtype="f") cls.data1d = cls.image[0] cls.data2d = cls.image cls.data3d = np.tile(cls.image[224:-224, 224:-224], (62, 1, 1)) cls.kernel1d = gaussian_kernel(1.0) cls.kernel2d = np.outer(cls.kernel1d, cls.kernel1d) cls.kernel3d = np.multiply.outer(cls.kernel2d, cls.kernel1d) cls.ctx = ocl.create_context() cls.tol = { "1D": 1e-4, "2D": 1e-3, "3D": 1e-3, }
def test_identity2(): from scipy.misc import ascent from scipy.ndimage.interpolation import zoom im = zoom(ascent().astype(np.float32), (2, 2)) Ng = 32 Ny, Nx = im.shape h = np.zeros_like(im) h[Ny // Ng // 2::Ny // Ng, Nx // Ng // 2::Nx // Ng] = 1. out = convolve_spatial2(im, h, grid_dim=(Ng, Ng), pad_factor=3) #npt.assert_almost_equal(im, out, decimal = 3) return im, out, h
def __init__(self, cortes): self.imagen = np.array(misc.ascent()) self.mostrar_imagen_original() self.cortes_imagen = [] #tipo list self.cortar_imagen() self.imagen_original_array = np.array(self.cortes_imagen) #convierto en np array self.imagen_auxiliar = np.copy(self.imagen_original_array) self.imagen_auxiliar[0,0]= np.zeros_like(self.imagen_auxiliar[0,0]) #lleno primer elemento siempre de ceros, #a partir de aqui esta ordenada, pero con la primera posición de la matriz #llena de ceros, con esta voy a comparar cuando esté ordenada. self.lista_imagen = np.copy(self.imagen_auxiliar) #este es el array con el que voy a trabajar para mover las fichas self.array_ceros = [0,0] self.reordenar_imagen() self.mostrar_imagen_desordenada() self.iniciar_juego()
def cuantizar(): imagen = misc.ascent() (n, m) = imagen.shape imagen_original = imagen[::] for k in range(1, 9): rango = int(256 / pow(2, k)) imagen = np.floor(np.divide(imagen, rango)) imagen = np.floor(np.multiply(imagen, rango)) imagen = np.add(imagen, rango / 2) plt.imshow(imagen, cmap=plt.cm.gray) plt.xticks([]) plt.yticks([]) plt.show() print("Ratio: ", ratio(n, rango, 256, k * 3)) print("Sigma: ", np.sqrt(sum(sum((imagen_original - imagen)**2))) / (n * m)) imagen = imagen_original[::]
def main(): pub = rospy.Publisher('image', Image, queue_size=1) # lena is no longer available since 0.17 due to license issue if LooseVersion(scipy.__version__) >= LooseVersion("0.17"): img = cv2.cvtColor(ascent().astype(np.uint8), cv2.COLOR_GRAY2BGR) else: img = cv2.cvtColor(lena().astype(np.uint8), cv2.COLOR_GRAY2BGR) bridge = cv_bridge.CvBridge() msg = bridge.cv2_to_imgmsg(img, encoding='bgr8') msg.header.frame_id = 'camera' # publish in 30 hz rate = rospy.Rate(30) while not rospy.is_shutdown(): msg.header.stamp = rospy.get_rostime() pub.publish(msg) rate.sleep()
def do_scipy_laplace(): image = cv2.imread(f"sampled_images_interpolated.png") image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) def derivative2(input, axis, output, mode, cval): return correlate1d(input, [-1, 2, -1], axis, output, mode, cval, 0) image2 = generic_laplace(image, derivative2, output=None, mode="reflect", cval=0.0) cv2.imwrite("scipy_laplace.png", image2) from scipy import ndimage, misc ascent = misc.ascent() result = ndimage.laplace(ascent) cv2.imwrite("ascent.png", ascent) cv2.imwrite("result.png", result)
def main(): image = misc.ascent() # image in size 512 * 512 k = 0 y_ratio = [] y_distance = [] while k < IMAGE_SIZE : # Use the SVD to zero all but the k largest singular-values # Reconstruct the rank-k approximation matrix compressed_image, s = compress_svd(image, k) if k in [16, 32, 64, 128, 256]: imshow(compressed_image, cmap='gray') title("k="+str(k)) show() # For each k calculate the compression ratio image_rank = np.linalg.matrix_rank(image) ratio = compressing_ratio(IMAGE_SIZE, k, image_rank) y_ratio += [ratio] # For each k calculate the Frobenius distance between the original and the reconstructed # images. Use numpy.linalg.norm. distance = frobenius_distance(image, compressed_image) y_distance += [distance] k += 1 # graph of the Frobenius distance a function of k plot(y_distance) title("Frobenius distance a function of k") ylabel("Frobenius distance") xlabel("k") show() # graph of the compression ratio a function of k plot(y_ratio) title("compression ratio a function of k") ylabel("compression ratio") xlabel("k") show()
def test_minimum_spanning_stream(): # loading test image im = ascent() img = im[250:350] # initializing streaming generator gen = HorizontalStreaming(img) stream = gen.generate_stream(block_shape=(100, 100)) curr_img = None stable_graph = None for n, (t, e, i) in enumerate(streaming_spanning_tree_v2(stream, return_img=True)): if n == 0: curr_img = i stable_graph = t else: curr_img = stick_two_images(curr_img, i, num_overlapping=1, direction='H') stable_graph = resize_graph(stable_graph, t.shape) stable_graph += t # extracting real minimum spanning tree real_mst = minimum_spanning_tree(img_to_graph(curr_img)) if e is not None: mst = stable_graph + e else: # last iteration mst = stable_graph # testing that the mst found using our algorithm is always connected ncc, _ = connected_components(mst) assert ncc == 1 # asserting that the mst found is a tree (=> thus spans all nodes) assert mst.nnz == (mst.shape[0] - 1) # asserting that mst is minimal assert np.around(mst.sum(), decimals=9) == np.around(real_mst.sum(), decimals=9)
def setup_method(self, method): ref_image = ascent() center = np.array((256, 256)) shifts = np.array([(0.0, 0.0), (4.3, 2.13), (1.65, 3.58), (-2.3, 2.9), (5.2, -2.1), (2.7, 2.9), (5.0, 6.8), (-9.1, -9.5), (-9.0, -9.9), (-6.3, -9.2)]) s = hs.signals.Signal2D(np.zeros((10, 100, 100))) for i in range(10): # Apply each sup-pixel shift using FFT and InverseFFT offset_image = fourier_shift(np.fft.fftn(ref_image), shifts[i]) offset_image = np.fft.ifftn(offset_image).real # Crop central regions of shifted images to avoid wrap around s.data[i, ...] = offset_image[center[0]:center[0] + 100, center[1]:center[1] + 100] self.signal = s self.shifts = shifts
def test_streams(self): """ Test multiple FFT in // with different streams. :return: """ for dtype in [np.complex64, np.complex128]: if dtype == np.complex64: rtol = 1e-6 else: rtol = 1e-12 d = ascent().astype(dtype) n_streams = 5 vd = [] vapp = [] for i in range(n_streams): vd.append(cua.to_gpu(np.roll(d, i * 7, axis=1))) vapp.append( VkFFTApp(d.shape, d.dtype, ndim=2, norm=1, stream=cu_drv.Stream())) for i in range(n_streams): vapp[i].fft(vd[i]) for i in range(n_streams): dn = fftn(np.roll(d, i * 7, axis=1)) self.assertTrue( np.allclose(dn, vd[i].get(), rtol=rtol, atol=abs(dn).max() * rtol)) for i in range(n_streams): vapp[i].ifft(vd[i]) for i in range(n_streams): dn = np.roll(d, i * 7, axis=1) self.assertTrue( np.allclose(dn, vd[i].get(), rtol=rtol, atol=abs(dn).max() * rtol))
def construct(sigma: float=0.1, mu: float=0.1) -> Tuple["TVDenoisingProblem", Matrix]: """Construct a sample total-variation denoising problem using the standard SciPy test image `ascent`. :param sigma: The noise level in the image (default: 0.1) :param mu: The regularization parameter (default: 0.01) :return: An example of this type of problem and a good initial guess for its solution """ # Generate an image M = ascent().astype(float) # Normalize M M /= np.max(M) # Add noise M += sigma * np.random.randn(*M.shape) # Initial iterate Y0 = np.zeros(M.shape + (2,)) return TVDenoisingProblem(M, mu), Y0
def compress_image(samples): ascent = misc.ascent() # image to matrix rank = matrix_rank(ascent) u, singular_values, v = svd(ascent) # SVD for the image sigma_k_diag = zeros( 512) # init main diagonal for the reconstruct sigma_k matrix # init lists for graphs compression_ratio_arr, frobenius_distance_arr, x_axis = [0] * 512, [ 0 ] * 512, [0] * 512 for k in range(0, 512, 1): x_axis[k] = k sigma_k_diag[: k] = singular_values[: k] # set the k largest singular values and the rest are zero sigma_k = diag( sigma_k_diag ) # reconstruct sigma_k matrix with main diagonal with k largest singular values # reconstruct approximation matrix Mk = U Sk V^t u_sigma_k_product = dot(u, sigma_k) approximation_matrix = dot(u_sigma_k_product, v) compression_ratio_arr[k] = k / rank # compression ratio frobenius_distance_arr[k] = norm(ascent - approximation_matrix) # show 5 samples of compression of image if k in samples: subplot(111) title('K: ' + str(k) + ', cr rate: ' + str(compression_ratio_arr[k]) + ', fro rate: ' + str(frobenius_distance_arr[k]), fontsize=8) imshow(approximation_matrix) show() # graphs of compression ratio and frobenius distance ratio_compression_graphs(x_axis, frobenius_distance_arr, compression_ratio_arr)
def __init__(self, model=simulator, image=np.uint8(np.flipud(ascent()))): self.sim=model(image) self.data = image self.dim_xy_r=(self.data.shape[0],self.data.shape[1],self.data.shape[0]/self.data.shape[1]) self.__paused = False glutInit(sys.argv) # Create a double-buffer RGBA window glutInitDisplayMode(GLUT_DOUBLE) glutInitWindowPosition(0, 0) #position upper left corner on screen # Scale up the window (will increase visibility of pixels) glutInitWindowSize(self.dim_xy_r[0]*4,self.dim_xy_r[1]*4) # Create a window, setting its title glutCreateWindow('interactive') # Set the display callback. glutDisplayFunc(self.__DrawGLScene) # Setup the 'logic control' glutIdleFunc(self.__IdleFunction) # Handle window rescaling glutReshapeFunc(self.__ReSizeGLScene) # Control user input glutKeyboardFunc(self.__keyPressed) glutSpecialFunc(self.__keyPressed) glutMouseFunc(self.__mousePressed) glutPassiveMotionFunc(self.__mousePassPos) glutMotionFunc(self.__mousePos) # Prepare texture (we only use one in total here) texture=glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texture) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) #GL_NEAREST or GL_LINEAR (GL_NEAREST, because we like pixel-graphics in this example) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) # Run the GLUT main loop until the user closes the window. glutMainLoop()
def cuantizar2(): imagen = misc.ascent() imagen_original = imagen[::] k = 2 bloque_pixeles = int(512 / 8) bloque_tamano = 8 for i in range(0, bloque_pixeles): for j in range(0, bloque_pixeles): lista = imagen[bloque_tamano * i:bloque_tamano * (i + 1), bloque_tamano * j:bloque_tamano * (j + 1)] maximo = np.max(lista) minimo = np.min(lista) lista = np.add(lista, -minimo) rango = int((maximo - minimo) / pow(2, k)) lista = np.add(lista, minimo + rango / 2) imagen[bloque_tamano * i:bloque_tamano * (i + 1), bloque_tamano * j:bloque_tamano * (j + 1)] = lista plt.imshow(imagen, cmap=plt.cm.gray) plt.xticks([]) plt.yticks([]) plt.show() print("Sigma: ", np.sqrt(sum(sum((imagen_original - imagen)**2))) / (n * m))
def main(): # Downsample the testimage by a factor of 2 bw_image=np.uint8(np.flipud(ascent()))[::2,::2] rgb_image=np.zeros([*bw_image.shape,3],dtype=np.uint8) rgb_image[:,:,:]=bw_image[:,:,np.newaxis] glwindow(image=rgb_image)
## dic14-im02.py : importing and displaying py predefined images ## SXD 520 import pylab from scipy import misc # Synonyms show = pylab.show() load = pylab.imshow Ascent = misc.ascent() Lena = misc.lena() Face = misc.face('L') gray = pylab.gray() im = Ascent load(im,cmap=gray) show
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np from pywt import wavedec, wavedec2, waverec, waverec2, swt, swt2 try: from pywt import iswt, iswt2 except ImportError: # nigma/pywt iswt = None iswt2 = None try: from scipy.misc import ascent scipy_img = ascent() except ImportError: from scipy.misc import lena scipy_img = lena() def iDivUp(a, b): return (a + (b - 1))//b def create_data_to_good_size(data, size): """ From a numpy array, create a second numpy array with a given size. The result contains the tiled data, which is then cropped to the wanted size. """ # For 1D if min(size) == 1:
from PIL import Image from numpy import * from pylab import * from scipy.ndimage import filters from scipy import misc images = [misc.lena(), misc.face(), misc.ascent()] def gaussian(image, sigma): out = zeros(image.shape) if (isinstance(image[0][0], list)): for i in range(3): out[:, :, i] = filters.gaussian_filter(image[:, :, i], sigma) else: out = filters.gaussian_filter(image, sigma) return uint8(out) figure() gray() for i in range(len(images)): subplot(len(images), 2, 2 * i + 1) axis('off') imshow(images[i]) sigma = 20 quotientImage = images[i] / gaussian(images[i], sigma) subplot(len(images), 2, 2 * i + 2) axis('off') imshow(quotientImage)
from scipy import misc img1 = misc.face() img2 = misc.lena() img3 = misc.ascent() misc.imshow(img1) misc.imshow(img2) misc.imshow(img3)
def setUp(self): if ocl is None: return self.data = ascent().astype(numpy.float32) self.medianfilter = medfilt.MedianFilter2D(self.data.shape, devicetype="gpu")
plt.close('all') ############################################################################### ############################################################################### ### VECTOR QUANTIZATION USING K-MEANS (IMAGE SIZE REDUCTION) # http://scikit-learn.org/stable/tutorial/statistical_inference/unsupervised_learning.html # The goal is to choose a small number of exemplars to compress the information import scipy as sp # Import the data (a nxn matrix of greyscale values that represent a picture) try: lena = sp.lena() except AttributeError: from scipy import misc lena = misc.ascent() # Reshape the nxn matrix into a nx(1,n) shape; which is n vector of 1xn dimension. # Each vector is one row in the image. X = lena.reshape((-1, 1)) # We need an (n_sample, n_feature) array # Fit the k-means model k_means = cluster.KMeans(n_clusters=5, n_init=1) k_means.fit(X) values = k_means.cluster_centers_.squeeze() labels = k_means.labels_ # Construct the new vector by choosing the cluster centers values # for each element based on the cluster label. This is similar to R's 'score' attribute. lena_compressed = np.choose(labels, values)
from scipy import misc import itertools import math def gradient(image): imx = zeros(image.shape) imy = zeros(image.shape) filters.sobel(image, 1, imx) filters.sobel(image, 0, imy) angles = arctan2(imy, imx) return (sqrt(imx ** 2 + imy ** 2), angles) im = misc.ascent() (magnitude, angles) = gradient(im) averageMag = average(magnitude) figure() axis('off') gray() imshow(im) sameAngle = vectorize(lambda angle, lowerBound, upperBound: 255 if angle >= lowerBound and angle <= upperBound else 0) bins = [-pi, -pi * 3 / 4, -pi / 2, -pi / 4, 0, pi / 4, pi / 2, pi * 3 / 4, pi] maskedAngles = (magnitude>averageMag)*angles
def test_ascent(): assert_equal(ascent().shape, (512, 512))
import scipy.misc as misc import matplotlib.pyplot as plt img1 = misc.face() img2 = misc.ascent() img3 = misc.lena() titles = ['face', 'ascent', 'lena'] images = [img1, img2, img3] plt.subplot(1, 3, 1) plt.imshow(images[0]) plt.axis('off') plt.title(titles[0]) plt.subplot(1, 3, 2) plt.imshow(images[1], cmap='gray') plt.axis('off') plt.title(titles[1]) plt.subplot(1, 3, 3) plt.imshow(images[2], cmap='gray') plt.axis('off') plt.title(titles[2]) plt.show()
for j in range(Nf2, N - Nf2): num = 0 for ii in range(Mf): for jj in range(Nf): num += (filt[Mf-1-ii, Nf-1-jj] * image[i-Mf2+ii,j-Nf2+jj]) result[i, j] = num @jit(nopython=True) def filter2d(image, filt): result = numpy.zeros_like(image) filter2d_core(image, filt, result) return result image = ascent().astype(numpy.float64) filter = ones((7,7), dtype=image.dtype) result = filter2d(image, filter) # warm up from timeit import default_timer as time start = time() result = filter2d(image, filter) duration = time() - start from scipy.ndimage import convolve start = time() result2 = convolve(image, filter) duration2 = time() - start
def load_image(): return sm.ascent().astype(np.float32)