def test_connect_regions(): try: face = sp.face(gray=True) except AttributeError: # Newer versions of scipy have face in misc from scipy import misc face = misc.face(gray=True) for thr in (50, 150): mask = face > thr graph = img_to_graph(face, mask) assert_equal(ndimage.label(mask)[1], connected_components(graph)[0])
def test_connect_regions(): try: face = sp.face(gray=True) except AttributeError: # Newer versions of scipy have face in misc from scipy import misc face = misc.face(gray=True) # subsample by 4 to reduce run time face = face[::4, ::4] for thr in (50, 150): mask = face > thr graph = img_to_graph(face, mask) assert ndimage.label(mask)[1] == connected_components(graph)[0]
def test_connect_regions_with_grid(): try: face = sp.face(gray=True) except AttributeError: # Newer versions of scipy have face in misc from scipy import misc face = misc.face(gray=True) mask = face > 50 graph = grid_to_graph(*face.shape, mask=mask) assert_equal(ndimage.label(mask)[1], connected_components(graph)[0]) mask = face > 150 graph = grid_to_graph(*face.shape, mask=mask, dtype=None) assert_equal(ndimage.label(mask)[1], connected_components(graph)[0])
def _downsampled_face(): try: face = sp.face(gray=True) except AttributeError: # Newer versions of scipy have face in misc from scipy import misc face = misc.face(gray=True) face = face.astype(np.float32) face = face[::2, ::2] + face[1::2, ::2] + face[::2, 1::2] + face[1::2, 1::2] face = face[::2, ::2] + face[1::2, ::2] + face[::2, 1::2] + face[1::2, 1::2] face = face.astype(np.float32) face /= 16.0 return face
def _downsampled_face(): try: face = sp.face(gray=True) except AttributeError: # Newer versions of scipy have face in misc from scipy import misc face = misc.face(gray=True) face = face.astype(np.float32) face = (face[::2, ::2] + face[1::2, ::2] + face[::2, 1::2] + face[1::2, 1::2]) face = (face[::2, ::2] + face[1::2, ::2] + face[::2, 1::2] + face[1::2, 1::2]) face = face.astype(np.float32) face /= 16.0 return face
def test_connect_regions_with_grid(): try: face = sp.face(gray=True) except AttributeError: # Newer versions of scipy have face in misc from scipy import misc face = misc.face(gray=True) # subsample by 4 to reduce run time face = face[::4, ::4] mask = face > 50 graph = grid_to_graph(*face.shape, mask=mask) assert ndimage.label(mask)[1] == connected_components(graph)[0] mask = face > 150 graph = grid_to_graph(*face.shape, mask=mask, dtype=None) assert ndimage.label(mask)[1] == connected_components(graph)[0]
# License: BSD 3 clause import numpy as np import scipy as sp import matplotlib.pyplot as plt from sklearn import cluster from sklearn.utils.testing import SkipTest from sklearn.utils.fixes import sp_version if sp_version < (0, 12): raise SkipTest("Skipping because SciPy version earlier than 0.12.0 and " "thus does not include the scipy.misc.face() image.") try: face = sp.face(gray=True) except AttributeError: # Newer versions of scipy have face in misc from scipy import misc face = misc.face(gray=True) n_clusters = 5 np.random.seed(0) X = face.reshape((-1, 1)) # We need an (n_sample, n_feature) array k_means = cluster.KMeans(n_clusters=n_clusters, n_init=4) k_means.fit(X) values = k_means.cluster_centers_.squeeze() labels = k_means.labels_ # create an array from labels and values
import scipy as sp import matplotlib.pyplot as plt from sklearn.feature_extraction import image from sklearn.cluster import spectral_clustering from sklearn.utils.testing import SkipTest from sklearn.utils.fixes import sp_version if sp_version < (0, 12): raise SkipTest("Skipping because SciPy version earlier than 0.12.0 and " "thus does not include the scipy.misc.face() image.") # load the raccoon face as a numpy array try: face = sp.face(gray=True) except AttributeError: # Newer versions of scipy have face in misc from scipy import misc face = misc.face(gray=True) # Resize it to 10% of the original size to speed up the processing face = sp.misc.imresize(face, 0.10) / 255. # Convert the image into a graph with the value of the gradient on the # edges. graph = image.img_to_graph(face) # Take a decreasing function of the gradient: an exponential # The smaller beta is, the more independent the segmentation is of the # actual image. For beta=1, the segmentation is close to a voronoi
import scipy as sp from scipy.ndimage.filters import gaussian_filter import matplotlib.pyplot as plt from skimage import img_as_float from skimage.transform import rescale from sklearn.feature_extraction import image from sklearn.cluster import spectral_clustering # load the raccoon face as a numpy array try: # SciPy >= 0.16 have face in misc from scipy.misc import face orig_face = img_as_float(face(gray=True)) except ImportError: orig_face = img_as_float(sp.face(gray=True)) # Resize it to 10% of the original size to speed up the processing # Applying a Gaussian filter for smoothing prior to down-scaling # reduces aliasing artifacts. smoothened_face = gaussian_filter(orig_face, sigma=4.5) rescaled_face = rescale(smoothened_face, 0.1, mode="reflect") # Convert the image into a graph with the value of the gradient on the # edges. graph = image.img_to_graph(rescaled_face) # Take a decreasing function of the gradient: an exponential # The smaller beta is, the more independent the segmentation is of the # actual image. For beta=1, the segmentation is close to a voronoi beta = 5
def plot_image_denoising(): try: # SciPy >= 0.16 have face in misc from scipy.misc import face face = face(gray=True) except ImportError: face = sp.face(gray=True) # Convert from uint8 representation with values between 0 and 255 to # a floating point representation with values between 0 and 1. face = face / 255. # downsample for higher speed face = face[::4, ::4] + face[1::4, ::4] + face[::4, 1::4] + face[1::4, 1::4] face /= 4.0 height, width = face.shape # Distort the right half of the image print('Distorting image...') distorted = face.copy() distorted[:, width // 2:] += 0.075 * np.random.randn(height, width // 2) # Extract all reference patches from the left half of the image print('Extracting reference patches...') t0 = time() patch_size = (7, 7) data = extract_patches_2d(distorted[:, :width // 2], patch_size) data = data.reshape(data.shape[0], -1) data -= np.mean(data, axis=0) data /= np.std(data, axis=0) print('done in %.2fs.' % (time() - t0)) # ############################################################################# # Learn the dictionary from reference patches print('Learning the dictionary...') t0 = time() dico = MiniBatchDictionaryLearning(n_components=100, alpha=1, n_iter=500) V = dico.fit(data).components_ dt = time() - t0 print('done in %.2fs.' % dt) plt.figure(figsize=(4.2, 4)) for i, comp in enumerate(V[:100]): plt.subplot(10, 10, i + 1) plt.imshow(comp.reshape(patch_size), cmap=plt.cm.gray_r, interpolation='nearest') plt.xticks(()) plt.yticks(()) plt.suptitle('Dictionary learned from face patches\n' + 'Train time %.1fs on %d patches' % (dt, len(data)), fontsize=16) plt.subplots_adjust(0.08, 0.02, 0.92, 0.85, 0.08, 0.23) # ############################################################################# # Display the distorted image def show_with_diff(image, reference, title): """Helper function to display denoising""" plt.figure(figsize=(5, 3.3)) plt.subplot(1, 2, 1) plt.title('Image') plt.imshow(image, vmin=0, vmax=1, cmap=plt.cm.gray, interpolation='nearest') plt.xticks(()) plt.yticks(()) plt.subplot(1, 2, 2) difference = image - reference plt.title('Difference (norm: %.2f)' % np.sqrt(np.sum(difference**2))) plt.imshow(difference, vmin=-0.5, vmax=0.5, cmap=plt.cm.PuOr, interpolation='nearest') plt.xticks(()) plt.yticks(()) plt.suptitle(title, size=16) plt.subplots_adjust(0.02, 0.02, 0.98, 0.79, 0.02, 0.2) show_with_diff(distorted, face, 'Distorted image') # ############################################################################# # Extract noisy patches and reconstruct them using the dictionary print('Extracting noisy patches... ') t0 = time() data = extract_patches_2d(distorted[:, width // 2:], patch_size) data = data.reshape(data.shape[0], -1) intercept = np.mean(data, axis=0) data -= intercept print('done in %.2fs.' % (time() - t0)) transform_algorithms = [('Orthogonal Matching Pursuit\n1 atom', 'omp', { 'transform_n_nonzero_coefs': 1 }), ('Orthogonal Matching Pursuit\n2 atoms', 'omp', { 'transform_n_nonzero_coefs': 2 }), ('Least-angle regression\n5 atoms', 'lars', { 'transform_n_nonzero_coefs': 5 }), ('Thresholding\n alpha=0.1', 'threshold', { 'transform_alpha': .1 })] reconstructions = {} for title, transform_algorithm, kwargs in transform_algorithms: print(title + '...') reconstructions[title] = face.copy() t0 = time() dico.set_params(transform_algorithm=transform_algorithm, **kwargs) code = dico.transform(data) patches = np.dot(code, V) patches += intercept patches = patches.reshape(len(data), *patch_size) if transform_algorithm == 'threshold': patches -= patches.min() patches /= patches.max() reconstructions[title][:, width // 2:] = reconstruct_from_patches_2d( patches, (height, width // 2)) dt = time() - t0 print('done in %.2fs.' % dt) show_with_diff(reconstructions[title], face, title + ' (time: %.1fs)' % dt) plt.show()
import matplotlib.pyplot as plt from skimage import img_as_float from skimage.transform import rescale from sklearn.feature_extraction.image import grid_to_graph from sklearn.cluster import AgglomerativeClustering # ############################################################################# # Generate data try: # SciPy >= 0.16 have face in misc from scipy.misc import face orig_face = img_as_float(face(gray=True)) except ImportError: orig_face = img_as_float(sp.face(gray=True)) # Resize it to 10% of the original size to speed up the processing # Applying a Gaussian filter for smoothing prior to down-scaling # reduces aliasing artifacts. smoothened_face = gaussian_filter(orig_face, sigma=4.5) rescaled_face = rescale(smoothened_face, 0.1, mode="reflect") X = np.reshape(rescaled_face, (-1, 1)) # ############################################################################# # Define the structure A of the data. Pixels connected to their neighbors. connectivity = grid_to_graph(*rescaled_face.shape) # ############################################################################# # Compute clustering
# License: BSD 3 clause import numpy as np import scipy as sp import matplotlib.pyplot as plt from sklearn import cluster from sklearn.utils.testing import SkipTest from sklearn.utils.fixes import sp_version if sp_version < (0, 12): raise SkipTest("Skipping because SciPy version earlier than 0.12.0 and " "thus does not include the scipy.misc.face() image.") try: face = sp.face(gray=True) #type = 'numpy.ndarray' except AttributeError: # Newer versions of scipy have face in misc from scipy import misc face = misc.face(gray=True) n_clusters = 5 np.random.seed(0) X = face.reshape((-1, 1)) # We need an (n_sample, n_feature) array k_means = cluster.KMeans(n_clusters=n_clusters, n_init=4) k_means.fit(X) values = k_means.cluster_centers_.squeeze() labels = k_means.labels_
assert len(gen_class_vector.get_shape()) == 2 assert gen_class_vector.dtype == tf.float32 # assert宣告變數在程式某一段必須為某值 a = 0 assert a == 1 print(1) assert a == 0 print(0) # 實作k-means try: # SciPy >= 0.16 have face in misc from scipy.misc import face face = face(gray=True) except ImportError: face = sp.face(gray=True) # face是一張圖片,大小為768*1024 n_clusters = 5 np.random.seed(0) X = face.reshape((-1, 1)) # 拉成一維向量 (n_sample, n_feature) array k_means = cluster.KMeans(n_clusters=n_clusters, n_init=4) # K_means分類,num_cluster=5 k_means.fit(X) values = k_means.cluster_centers_.squeeze( ) # 使用不同 centroid seeds 運行 k-means 算法的時間 labels = k_means.labels_ face_compressed = np.choose(labels, values) #labels範圍0~4,長度768*1024,values代表五個k_keans值 face_compressed.shape = face.shape