Numpy Tutorial
Creating NumPy Array
NumPy Array Manipulation
Matrix in NumPy
Operations on NumPy Array
Reshaping NumPy Array
Indexing NumPy Array
Arithmetic operations on NumPy Array
Linear Algebra in NumPy Array
NumPy and Random Data
Sorting and Searching in NumPy Array
Universal Functions
Working With Images
Projects and Applications with NumPy
Generating a 2D Gaussian array (often called a Gaussian kernel) is commonly used in image processing, especially in blurring and edge detection. Here's a tutorial on how to create a 2D Gaussian array using NumPy.
First, you'll need NumPy:
pip install numpy
Now, import the necessary libraries:
import numpy as np import matplotlib.pyplot as plt
The 2D Gaussian function is given by:
f(x,y)=e−(x2+y2)/(2σ2)
Where:
def gaussian_2d(x, y, sigma=1.0): return np.exp(-(x**2 + y**2) / (2 * sigma**2))
To create the 2D Gaussian array:
def gaussian_kernel(size, sigma=1.0): kernel = np.fromfunction( lambda x, y: gaussian_2d(x - (size - 1) / 2, y - (size - 1) / 2, sigma), (size, size) ) return kernel / kernel.sum()
To see what our Gaussian kernel looks like, we can use the matplotlib
library:
size = 7 sigma = 1.0 kernel = gaussian_kernel(size, sigma) # Display the kernel plt.imshow(kernel, cmap="hot", interpolation="none") plt.colorbar(label="Intensity") plt.title(f"2D Gaussian Kernel (size={size}, sigma={sigma})") plt.show()
A 2D Gaussian array (or kernel) is crucial in various image processing tasks. With NumPy, generating and visualizing such a kernel is straightforward. By adjusting the size and sigma values, you can create Gaussian kernels suited to different requirements and observe their shapes and intensities.
Generate a 2D Gaussian array using the numpy.random.normal
function.
import numpy as np # Generate a 2D Gaussian array mean = [0, 0] covariance_matrix = [[1, 0.5], [0.5, 1]] gaussian_array = np.random.multivariate_normal(mean, covariance_matrix, size=(3, 3)) # Display the 2D Gaussian array print("2D Gaussian Array:") print(gaussian_array)
Create a 2D Gaussian matrix with specified mean and standard deviation.
import numpy as np # Create a 2D Gaussian matrix mean = [0, 0] std_dev = 1 gaussian_matrix = np.random.normal(mean, std_dev, size=(3, 3)) # Display the 2D Gaussian matrix print("2D Gaussian Matrix:") print(gaussian_matrix)
Apply a 2D Gaussian filter to an image using scipy.ndimage.gaussian_filter
.
import numpy as np from scipy.ndimage import gaussian_filter import matplotlib.pyplot as plt # Generate a sample image image = np.random.random((100, 100)) # Apply a 2D Gaussian filter to the image sigma = 1.0 smoothed_image = gaussian_filter(image, sigma=sigma) # Display the original and smoothed images plt.subplot(1, 2, 1) plt.imshow(image, cmap='gray') plt.title('Original Image') plt.subplot(1, 2, 2) plt.imshow(smoothed_image, cmap='gray') plt.title('Smoothed Image') plt.show()
Generate a 2D Gaussian kernel using scipy.ndimage.gaussian_filter
and numpy.meshgrid
.
import numpy as np import matplotlib.pyplot as plt # Generate a 2D Gaussian kernel x, y = np.meshgrid(np.linspace(-2, 2, 5), np.linspace(-2, 2, 5)) gaussian_kernel = np.exp(-(x**2 + y**2) / (2 * 1.0**2)) / (2 * np.pi * 1.0**2) # Display the 2D Gaussian kernel plt.imshow(gaussian_kernel, cmap='viridis', interpolation='none') plt.title('2D Gaussian Kernel') plt.colorbar() plt.show()
Generate a 2D Gaussian distribution using numpy.random.multivariate_normal
.
import numpy as np import matplotlib.pyplot as plt # Generate a 2D Gaussian distribution mean = [0, 0] covariance_matrix = [[1, 0.5], [0.5, 1]] samples = np.random.multivariate_normal(mean, covariance_matrix, size=1000) # Plot the 2D Gaussian distribution plt.scatter(samples[:, 0], samples[:, 1], alpha=0.5) plt.title('2D Gaussian Distribution') plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.show()
Create a 2D Gaussian distribution using numpy.random.multivariate_normal
.
import numpy as np # Generate a 2D Gaussian distribution mean = [0, 0] covariance_matrix = [[1, 0.5], [0.5, 1]] gaussian_distribution = np.random.multivariate_normal(mean, covariance_matrix, size=(3, 3)) # Display the 2D Gaussian distribution print("2D Gaussian Distribution:") print(gaussian_distribution)
Generate a random 2D Gaussian array using numpy.random.normal
.
import numpy as np # Generate a random 2D Gaussian array mean = [0, 0] std_dev = 1 random_gaussian_array = np.random.normal(mean, std_dev, size=(3, 3)) # Display the random 2D Gaussian array print("Random 2D Gaussian Array:") print(random_gaussian_array)
Plot a 2D Gaussian distribution using numpy.meshgrid
and matplotlib.pyplot.contour
.
import numpy as np import matplotlib.pyplot as plt # Generate a 2D Gaussian distribution mean = [0, 0] covariance_matrix = [[1, 0.5], [0.5, 1]] x, y = np.meshgrid(np.linspace(-3, 3, 100), np.linspace(-3, 3, 100)) pos = np.dstack((x, y)) z = np.exp(-(np.linalg.solve(covariance_matrix, pos.reshape(-1, 2).T).T * pos.reshape(-1, 2)).sum(axis=1) / 2) / \ (2 * np.pi * np.sqrt(np.linalg.det(covariance_matrix))) z = z.reshape(100, 100) # Plot the 2D Gaussian distribution plt.contour(x, y, z, cmap='viridis') plt.title('2D Gaussian Distribution Plot') plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.show()
Generate a 2D Gaussian array with a custom mean and covariance using numpy.random.multivariate_normal
.
import numpy as np # Generate a 2D Gaussian array with custom mean and covariance custom_mean = [2, -1] custom_covariance_matrix = [[2, 0.8], [0.8, 1]] custom_gaussian_array = np.random.multivariate_normal(custom_mean, custom_covariance_matrix, size=(4, 4)) # Display the custom 2D Gaussian array print("Custom 2D Gaussian Array:") print(custom_gaussian_array)