Skip to main content

Implementing BFS in Java

In this post, we implement Breadth-First Search (BFS) in Java using an adjacency matrix. BFS is a fundamental graph traversal algorithm that visits all nodes level by level, starting from a source node and exploring all its direct neighbours before moving deeper into the graph. It is widely used in shortest path problems, network analysis, and AI search strategies. What is BFS? BFS explores a graph by using a queue data structure. It starts at a chosen node (node 1 in our implementation), adds it to the queue, and then repeatedly dequeues a node, visits all its unvisited neighbours, and enqueues them. This guarantees that all nodes at depth d are visited before any node at depth d+1. The graph in this implementation is represented as an adjacency matrix — a 2D array where m[i][j] = 1 means there is an edge between node i+1 and node j+1, and 0 means no edge.

Program for Threshold in MATLAB

In this post, we implement image thresholding in MATLAB. Thresholding is one of the simplest and most widely used segmentation techniques. It converts a grayscale image into a binary image by comparing each pixel's intensity against a threshold value: pixels below the threshold are set to 0 (black) and pixels at or above the threshold are set to 255 (white). This cleanly separates foreground objects from the background. MATLAB Code % Image Thresholding in MATLAB % Converts a grayscale image to binary using a user-supplied threshold. % Pixels below the threshold -> 0 (black) % Pixels >= threshold -> 255 (white) clc; % Clear the command window clear all; % Clear all workspace variables % --- Load image --- % Place your image in the MATLAB working directory. originalImage = imread('sample.jpg'); % Read the colour image grayImage = rgb2gray(originalImage); % Convert to grayscale imageSize = size(grayImage); % [rows, cols] % --- Get threshold from user --- thresholdValue = input('Enter threshold value (0-255) : '); % e.g. 128 % --- Apply threshold --- binaryImage = grayImage; % Copy to preserve border pixels for i = 1 : imageSize(1) for j = 1 : imageSize(2) if grayImage(i, j) black else binaryImage(i, j) = 255; % At or above threshold -> white end end end % --- Display results --- subplot(1, 2, 1); imshow(grayImage); title('Original Grayscale Image'); subplot(1, 2, 2); imshow(binaryImage); title(['Thresholded at ', num2str(thresholdValue)]);

MATLAB Program to Implement LPF

In this post, we implement a spatial-domain Low Pass Filter (LPF) in MATLAB using a 3×3 averaging kernel. A low pass filter smooths an image by replacing each pixel with the average of itself and its 8 neighbours. This reduces noise and high-frequency detail (sharp edges), producing a blurred version of the original. It is the spatial counterpart of frequency-domain low-pass filtering and is the basis of many image smoothing techniques. MATLAB Code % Low Pass Filter (LPF) in MATLAB % Applies a 3x3 averaging kernel (box filter) to a grayscale image. % Each output pixel is the mean of the 3x3 neighbourhood centred on it. clc; % Clear the command window clear all; % Clear all workspace variables % --- Load image --- % Place your image in the MATLAB working directory. originalImage = imread('sample.jpg'); % Read the colour image grayImage = rgb2gray(originalImage); % Convert to grayscale imageSize = size(grayImage); % [rows, cols] % Initialise the output image (same size as input) lpfImage = grayImage; % --- Apply 3x3 averaging kernel --- % Skip the border row/column (index 1 and last) to avoid out-of-bounds access. for i = 2 : imageSize(1) - 1 for j = 2 : imageSize(2) - 1 % Sum the 3x3 neighbourhood and divide by 9 (average) lpfImage(i, j) = ( ... double(grayImage(i-1, j-1)) + double(grayImage(i-1, j)) + double(grayImage(i-1, j+1)) + ... double(grayImage(i, j-1)) + double(grayImage(i, j)) + double(grayImage(i, j+1)) + ... double(grayImage(i+1, j-1)) + double(grayImage(i+1, j)) + double(grayImage(i+1, j+1)) ... ) / 9; end end % --- Display results --- subplot(1, 2, 1); imshow(grayImage); title('Original Grayscale Image'); subplot(1, 2, 2); imshow(lpfImage); title('Low Pass Filtered (Blurred)');

Implementation of Histogram Processing in MATLAB

In this post, we implement Histogram Equalisation in MATLAB. Histogram equalisation is an image enhancement technique that redistributes the pixel intensity values of an image so that the resulting histogram is approximately uniform. This increases the global contrast of the image, especially when the usable image data is represented by close contrast values. It is widely used in medical imaging, satellite imagery, and photography. MATLAB Code % Histogram Equalisation in MATLAB % Reads a colour image, converts to grayscale, reduces contrast % intentionally (to simulate a low-contrast image), applies % histogram equalisation, and displays both images with their histograms. clc; % Clear the command window clear all; % Clear all workspace variables % --- Load and prepare image --- % Place your image in the MATLAB working directory. originalImage = imread('sample.jpg'); % Read the colour image grayImage = rgb2gray(originalImage); % Convert to grayscale grayImage = imresize(grayImage, [256, 256]); % Resize to 256x256 % Reduce contrast by scaling pixel values to half range (simulate low contrast) lowContrastImage = uint8(0.5 * double(grayImage)); % --- Apply histogram equalisation --- % histeq() redistributes intensity values to flatten the histogram. equalizedImage = histeq(lowContrastImage, 256); % --- Display results: images and histograms --- figure; subplot(2, 2, 1); imshow(lowContrastImage); title('Low Contrast (Original)'); subplot(2, 2, 2); imshow(equalizedImage); title('Histogram Equalised'); subplot(2, 2, 3); imhist(lowContrastImage); title('Original Histogram'); subplot(2, 2, 4); imhist(equalizedImage); title('Equalised Histogram');

Implementing HPF in MATLAB

In this post, we implement a spatial-domain High Pass Filter (HPF) in MATLAB. A high pass filter suppresses low-frequency (smooth) regions of an image and enhances high-frequency content such as edges and sharp transitions. Unlike the Low Pass Filter which blurs an image, the HPF makes edges more visible by computing the Laplacian of the image at every pixel. MATLAB Code % High Pass Filter (HPF) in MATLAB % Applies a 3x3 Laplacian high-pass kernel to a grayscale image. % The kernel: [-1 -1 -1; -1 8 -1; -1 -1 -1] % Computes: HPF(i,j) = 8*center - sum_of_8_neighbours clc; % Clear the command window clear all; % Clear all workspace variables % --- Load image --- % Place your image in the MATLAB working directory. originalImage = imread('hills.jpg'); % Read the colour image grayImage = rgb2gray(originalImage); % Convert to grayscale imageSize = size(grayImage); % [rows, cols] % Initialise output as double to avoid uint8 overflow hpfImage = double(grayImage); % --- Apply Laplacian HPF kernel --- % Skip the border pixels (row/col 1 and last row/col) % to avoid out-of-bounds indexing. for i = 2 : imageSize(1) - 1 for j = 2 : imageSize(2) - 1 % Laplacian: multiply centre by 8, subtract all 8 neighbours hpfImage(i, j) = ... -double(grayImage(i-1, j-1)) ... -double(grayImage(i-1, j )) ... -double(grayImage(i-1, j+1)) ... -double(grayImage(i, j-1)) ... +8*double(grayImage(i, j )) ... -double(grayImage(i, j+1)) ... -double(grayImage(i+1, j-1)) ... -double(grayImage(i+1, j )) ... -double(grayImage(i+1, j+1)); end end % --- Display results --- subplot(1, 2, 1); imshow(grayImage); title('Original Grayscale Image'); subplot(1, 2, 2); imshow(hpfImage, []); title('High Pass Filtered Image');

Implementing Edge Detection in MATLAB

In this post, we implement three popular edge detection algorithms in MATLAB: Canny, Prewitt, and Sobel. Edge detection is a critical step in image processing and computer vision — it identifies points where image brightness changes sharply, which typically corresponds to object boundaries. We apply all three detectors to the same input image and display the results side by side for comparison. MATLAB Code % Edge Detection in MATLAB: Canny, Prewitt, and Sobel % Applies three edge detectors to the same grayscale image % and displays all results in a 2x2 subplot grid. clc; % Clear the command window clear all; % Clear all workspace variables close all; % Close all open figure windows % --- Load image --- % 'cameraman.tif' is a standard MATLAB sample image. % Replace with any grayscale image in your working directory. originalImage = imread('cameraman.tif'); % --- Apply edge detectors --- % edge(I, 'method') returns a binary image: % 1 = edge pixel | 0 = non-edge pixel % Canny: optimal detector - good noise suppression, thin edges canny = edge(originalImage, 'canny'); % Prewitt: gradient-based, uses 3x3 horizontal/vertical kernels prewitt = edge(originalImage, 'prewitt'); % Sobel: similar to Prewitt but weights the central row/column more sobel = edge(originalImage, 'sobel'); % --- Display results --- figure; subplot(2, 2, 1); imshow(originalImage); title('Original Image'); subplot(2, 2, 2); imshow(canny); title('Canny Edge Detection'); subplot(2, 2, 3); imshow(prewitt); title('Prewitt Edge Detection'); subplot(2, 2, 4); imshow(sobel); title('Sobel Edge Detection');

Implementing DFT in MATLAB

In this post, we implement the Discrete Fourier Transform (DFT) in MATLAB using the built-in fft() function and plot the resulting frequency-domain representation of a user-supplied sequence. The DFT converts a finite-length discrete-time signal from the time domain into the frequency domain, revealing which frequency components are present and at what amplitudes. MATLAB Code % Implementing DFT in MATLAB using fft() % The user supplies a sequence and the DFT length. % The magnitude spectrum is plotted using stem(). clc; % Clear the command window clear all; % Clear all workspace variables % --- Input --- xSignal = input('Enter the input sequence (e.g. [0.25 0.25 0.25 0]) : '); nPoints = input('Enter the DFT length N : '); % --- Compute DFT --- % fft(x, N) computes the N-point FFT (a fast algorithm for the DFT). % If N > length(x), the sequence is zero-padded. % If N < length(x), the sequence is truncated. dftResult = fft(xSignal, nPoints); % --- Compute magnitude spectrum --- magnitude = abs(dftResult); % |X(k)| for each frequency bin k % --- Plot --- figure; subplot(1, 2, 1); stem(real(dftResult)); title('DFT - Real Part'); xlabel('Frequency Bin (k)'); ylabel('Re{X(k)}'); subplot(1, 2, 2); stem(imag(dftResult)); title('DFT - Imaginary Part'); xlabel('Frequency Bin (k)'); ylabel('Im{X(k)}'); % Display the magnitude spectrum in a separate figure figure; stem(magnitude); title('DFT Magnitude Spectrum |X(k)|'); xlabel('Frequency Bin (k)'); ylabel('|X(k)|');

Implementing DCT and IDCT in MATLAB

In this post, we implement the Discrete Cosine Transform (DCT) and its inverse (IDCT) on a grayscale image in MATLAB. The DCT is the mathematical backbone of JPEG image compression: it converts spatial pixel data into frequency coefficients, allowing low-energy (high-frequency) components to be discarded with minimal perceptual loss. The IDCT reconstructs the image from those coefficients. MATLAB Code % Implementing DCT and IDCT on an Image in MATLAB % Shows the original image, its DCT coefficient map, and the IDCT reconstruction. clc; % Clear the command window clear all; % Clear all workspace variables % --- Load and prepare image --- % Place your image in the MATLAB working directory. originalImage = imread('sample.jpg'); % Read the colour image grayImage = rgb2gray(originalImage); % Convert to grayscale [numRows, numCols] = size(grayImage); % Get image dimensions % --- Forward DCT (2D) --- % dct2() computes the 2-D Discrete Cosine Transform. % The output Y contains DCT coefficients (frequency domain). dctCoefficients = dct2(double(grayImage)); % Cast to double for precision % --- Inverse DCT --- % idct2() reconstructs the image from the DCT coefficients. % Ideally the reconstruction should match the original exactly. reconstructedImage = idct2(dctCoefficients); % --- Display results --- subplot(2, 3, 1); imshow(originalImage); title('Original Colour Image'); subplot(2, 3, 2); imshow(grayImage); title('Grayscale Image'); subplot(2, 3, 3); imshow(dctCoefficients, [0, 255]); title('DCT Coefficients'); subplot(2, 3, 4); imshow(reconstructedImage, [0, 255]); title('IDCT (Reconstructed)');

Implementing Digital Negative and Grayscale of Image in MATLAB

In this post, we implement two basic image transformations in MATLAB: converting a colour image to grayscale and producing its digital negative. The digital negative inverts the intensity of every pixel — dark areas become light and vice versa — by applying the transformation s = 255 - r to each pixel value r. These are fundamental point processing operations in digital image processing. MATLAB Code % Digital Negative and Grayscale of an Image in MATLAB % Demonstrates two point-processing transformations: % 1. RGB -> Grayscale % 2. Grayscale -> Digital Negative clc; % Clear the command window clear all; % Clear all workspace variables % --- Load the image --- % Place your image in the MATLAB working directory. originalImage = imread('desert.jpg'); % Read a colour (RGB) image % --- Convert to Grayscale --- grayImage = rgb2gray(originalImage); % Average the R, G, B channels % --- Compute Digital Negative --- % For an 8-bit image the maximum intensity is 255. % Negative: negative(x,y) = 255 - gray(x,y) negativeImage = 255 - grayImage; % Optionally save the negative image to disk imwrite(negativeImage, 'negative.jpg'); % --- Display all three images side by side --- subplot(1, 3, 1); imshow(originalImage); title('Original Colour Image'); subplot(1, 3, 2); imshow(grayImage); title('Grayscale Image'); subplot(1, 3, 3); imshow(negativeImage); title('Digital Negative');

Implementing Digital Negative of Image in MATLAB

In this post, we implement gray-level slicing in MATLAB — a point processing technique used in digital image processing to highlight a specific range of gray levels while suppressing everything outside that range. The program reads a grayscale image, asks the user to specify a lower and upper gray-level boundary, and produces two sliced images: one that preserves the background and one that blacks it out. MATLAB Code % Gray-Level Slicing in MATLAB % Highlights pixels within a user-defined gray-level range. % Two sliced versions are produced: % b - background preserved (pixels below r1 unchanged) % c - background suppressed (only the range [r1,r2] is shown in white) clc; % Clear the command window clear all; % Clear all workspace variables % --- Load image --- % Place your image file in the MATLAB working directory. originalImage = imread('sample.jpg'); % Read the image file grayImage = rgb2gray(originalImage); % Convert to grayscale imageSize = size(grayImage); % [rows, cols] % --- User inputs --- lowerLevel = input('Enter lower gray level : '); % e.g. 20 upperLevel = input('Enter upper gray level : '); % e.g. 50 % --- Slicing: preserve background --- % Pixels above upperLevel are set to 255 (white); others stay the same. slicedPreserve = grayImage; for row = 1:imageSize(1) for col = 1:imageSize(2) if grayImage(row, col) > lowerLevel if grayImage(row, col) > upperLevel slicedPreserve(row, col) = 255; % Highlight bright pixels end end end end % --- Slicing: suppress background --- % Pixels inside [lowerLevel, upperLevel] -> white; outside -> black. slicedSuppress = grayImage; for row = 1:imageSize(1) for col = 1:imageSize(2) if grayImage(row, col) > lowerLevel if grayImage(row, col) > upperLevel slicedSuppress(row, col) = 255; % In range -> white else slicedSuppress(row, col) = 0; % Out of range -> black end end end end % --- Display all three images side by side --- subplot(1, 3, 1); imshow(grayImage); title('Original Grayscale'); subplot(1, 3, 2); imshow(slicedPreserve); title('Sliced (Background Preserved)'); subplot(1, 3, 3); imshow(slicedSuppress); title('Sliced (Background Suppressed)');