# MATLAB Image Processing - Complete Command Reference
## **1. BASIC IMAGE I/O OPERATIONS**
### Reading and Writing Images
```matlab
% Read an image
img = imread('[Link]');
img = imread('[Link]');
img = imread('[Link]');
% Display image information
info = imfinfo('[Link]');
% Write image to file
imwrite(img, '[Link]');
imwrite(img, '[Link]', 'PNG');
imwrite(img, '[Link]');
% Display image
imshow(img);
figure, imshow(img); % Open in new figure
% Multiple images in same figure
subplot(1,2,1), imshow(img1), title('Image 1');
subplot(1,2,2), imshow(img2), title('Image 2');
```
## **2. IMAGE CONVERSION AND DATA TYPES**
### Type Conversions
```matlab
% Convert between classes
img_double = im2double(img); % Convert to double [0-1]
img_uint8 = im2uint8(img_double); % Convert to uint8 [0-255]
img_uint16 = im2uint16(img); % Convert to uint16 [0-65535]
img_single = im2single(img); % Convert to single
% Convert between color spaces
img_gray = rgb2gray(img_rgb); % RGB to grayscale
img_rgb = gray2rgb(img_gray); % Grayscale to RGB (replicated)
img_hsv = rgb2hsv(img_rgb); % RGB to HSV
img_rgb = hsv2rgb(img_hsv); % HSV to RGB
img_lab = rgb2lab(img_rgb); % RGB to L*a*b*
img_rgb = lab2rgb(img_lab); % L*a*b* to RGB
img_bw = im2bw(img_gray, 0.5); % Grayscale to binary (threshold
0.5)
% Indexed images
[X, map] = rgb2ind(img_rgb, 256); % RGB to indexed with 256 colors
img_rgb = ind2rgb(X, map); % Indexed to RGB
```
## **3. IMAGE DISPLAY AND VISUALIZATION**
### Display Options
```matlab
% Basic display with colormaps
imshow(img);
colormap(gray); % Grayscale colormap
colormap(jet); % Jet colormap
colormap(hot); % Hot colormap
colormap(cool); % Cool colormap
colorbar; % Add colorbar
% Image display with scaling
imshow(img, []); % Auto-scale display
imshow(img, [0 100]); % Display with specified range
% Montage display
montage({img1, img2, img3}); % Display multiple images
montage(img_cell_array, 'Size', [2 3]); % Specify grid size
% Image viewer tools
imtool(img); % Open in Image Tool
implay(img_sequence); % Play image sequence/video
% Custom display
imagesc(img); % Scale and display as image
axis image; % Equal aspect ratio
axis off; % Hide axes
```
## **4. IMAGE INFORMATION AND PROPERTIES**
### Image Statistics
```matlab
% Basic information
size(img) % Image dimensions
whos img % Variable information
ndims(img) % Number of dimensions
class(img) % Data type
% Pixel value statistics
max_val = max(img(:)) % Maximum pixel value
min_val = min(img(:)) % Minimum pixel value
mean_val = mean(img(:)) % Mean pixel value
std_val = std(double(img(:))) % Standard deviation
var_val = var(double(img(:))) % Variance
% Histogram
histogram = imhist(img); % Compute histogram
imhist(img); % Display histogram
histogram(img_gray, 256); % Display with 256 bins
% Profile
impixelinfo; % Interactive pixel info
improfile; % Intensity profile along line
pixel_values = impixel(img); % Get pixel values interactively
```
## **5. IMAGE ARITHMETIC OPERATIONS**
### Basic Operations
```matlab
% Addition
img_sum = imadd(img1, img2); % Add two images
img_sum = imadd(img, 50); % Add constant
% Subtraction
img_diff = imsubtract(img1, img2); % Subtract images
img_diff = imabsdiff(img1, img2); % Absolute difference
% Multiplication
img_product = immultiply(img1, img2); % Multiply images
img_product = immultiply(img, 1.5); % Multiply by constant
% Division
img_quotient = imdivide(img1, img2); % Divide images
img_quotient = imdivide(img, 2); % Divide by constant
% Complement
img_comp = imcomplement(img); % Image complement
(negative)
% Linear combination
img_combined = imlincomb(0.3, img1, 0.7, img2); % Weighted
combination
```
## **6. IMAGE ENHANCEMENT**
### Intensity Transformations
```matlab
% Contrast adjustment
img_adjusted = imadjust(img); % Auto contrast
img_adjusted = imadjust(img, [0.2 0.8], []); % Stretch specified
range
img_adjusted = imadjust(img, [0.2 0.8], [0 1], 2); % Gamma correction
% Histogram equalization
img_eq = histeq(img); % Global equalization
img_eq_adapt = adapthisteq(img); % Adaptive histogram
equalization
img_eq_adapt = adapthisteq(img, 'NumTiles', [8 8]); % Specify tiles
% Gamma correction
img_gamma = imadjust(img, [], [], 0.5); % Gamma < 1 (brighter)
img_gamma = imadjust(img, [], [], 1.5); % Gamma > 1 (darker)
% Thresholding
level = graythresh(img); % Otsu's threshold
img_bw = imbinarize(img); % Binary image
img_bw = imbinarize(img, level); % Binary with specified
threshold
img_bw = imbinarize(img, 'adaptive'); % Adaptive
thresholding
```
### Filtering and Smoothing
```matlab
% Linear filtering
h = fspecial('average', [5 5]); % Average filter
img_filtered = imfilter(img, h); % Apply filter
h_gaussian = fspecial('gaussian', [5 5], 1); % Gaussian filter
img_gaussian = imfilter(img, h_gaussian); % Apply Gaussian
% Non-linear filtering
img_median = medfilt2(img); % Median filter
img_median = medfilt2(img, [5 5]); % Specify
neighborhood
img_wiener = wiener2(img, [5 5]); % Wiener filter
% Custom filtering
kernel = [1 1 1; 1 -8 1; 1 1 1]; % Laplacian kernel
img_filtered = imfilter(img, kernel, 'replicate'); % Apply with border
handling
% Bilateral filtering
img_bilateral = imbilatfilt(img); % Edge-preserving
smoothing
img_bilateral = imbilatfilt(img, 0.5, 3); % Specify parameters
```
### Sharpening
```matlab
% Unsharp masking
img_sharp = imsharpen(img); % Basic sharpening
img_sharp = imsharpen(img, 'Radius', 2, 'Amount', 1); % Custom
sharpening
% Laplacian sharpening
kernel = [0 -1 0; -1 5 -1; 0 -1 0]; % Laplacian kernel
img_sharp = imfilter(img, kernel); % Apply sharpening
% High-boost filtering
kernel = [-1 -1 -1; -1 9 -1; -1 -1 -1]; % High-boost kernel
img_sharp = imfilter(img, kernel); % Apply high-boost
```
## **7. MORPHOLOGICAL OPERATIONS**
### Basic Morphology
```matlab
% Structuring elements
se_disk = strel('disk', 5); % Disk-shaped SE
se_square = strel('square', 5); % Square-shaped SE
se_line = strel('line', 10, 45); % Line-shaped SE
se_arbitrary = strel('arbitrary', [0 1 0; 1 1 1; 0 1 0]); % Custom SE
% Erosion and Dilation
img_eroded = imerode(img_bw, se_disk); % Erosion
img_dilated = imdilate(img_bw, se_disk); % Dilation
% Opening and Closing
img_opened = imopen(img_bw, se_disk); % Opening
(erosion then dilation)
img_closed = imclose(img_bw, se_disk); % Closing (dilation
then erosion)
% Morphological gradient
img_gradient = imdilate(img, se_disk) - imerode(img, se_disk); %
Morphological gradient
% Top-hat and bottom-hat
img_tophat = imtophat(img, se_disk); % Top-hat filtering
img_bothat = imbothat(img, se_disk); % Bottom-hat
filtering
```
### Advanced Morphology
```matlab
% Hit-or-miss transform
se1 = [1 1; 1 1]; % Foreground SE
se2 = [0 0; 0 0]; % Background SE
img_hitmiss = bwhitmiss(img_bw, se1, se2); % Hit-or-miss
% Thinning and thickening
img_thinned = bwmorph(img_bw, 'thin', inf); % Thinning
img_thickened = bwmorph(img_bw, 'thicken', inf); % Thickening
% Skeletonization
img_skel = bwmorph(img_bw, 'skel', inf); % Skeleton
img_skel = bwskel(img_bw); % Fast skeleton
% Distance transform
img_dist = bwdist(img_bw); % Distance transform
img_dist = bwdist(img_bw, 'euclidean'); % Euclidean
distance
% Watershed transform
img_watershed = watershed(img_dist); % Watershed
segmentation
```
## **8. IMAGE SEGMENTATION**
### Edge Detection
```matlab
% Sobel edge detection
edges_sobel = edge(img, 'sobel'); % Sobel method
edges_sobel = edge(img, 'sobel', 0.05); % With threshold
% Canny edge detection
edges_canny = edge(img, 'canny'); % Canny method
edges_canny = edge(img, 'canny', [0.1 0.3], 2); % Custom
parameters
% Other edge detectors
edges_prewitt = edge(img, 'prewitt'); % Prewitt
edges_roberts = edge(img, 'roberts'); % Roberts
edges_log = edge(img, 'log'); % Laplacian of
Gaussian
edges_zerocross = edge(img, 'zerocross'); % Zero-cross
edges_canny_auto = edge(img, 'canny', 'auto'); % Auto threshold
```
### Region-based Segmentation
```matlab
% Connected components
cc = bwconncomp(img_bw); % Find connected
components
stats = regionprops(cc, 'Area', 'Centroid', 'BoundingBox'); % Region
properties
labeled = bwlabel(img_bw); % Label connected
regions
% Active contours (snakes)
mask = false(size(img)); % Initial mask
mask(100:200, 100:200) = true; % Define ROI
img_seg = activecontour(img, mask, 300); % Active
contour
% K-means segmentation
[labels, centers] = imsegkmeans(img, 3); % K-means
clustering
segmented = labeloverlay(img, labels); % Overlay
segmentation
% Otsu's thresholding
level = graythresh(img); % Otsu threshold
img_seg = imbinarize(img, level); % Binary
segmentation
```
## **9. IMAGE RESTORATION**
### Noise Addition and Removal
```matlab
% Add noise
img_noisy = imnoise(img, 'gaussian', 0, 0.01); % Gaussian noise
img_noisy = imnoise(img, 'salt & pepper', 0.05); % Salt &
pepper noise
img_noisy = imnoise(img, 'speckle', 0.04); % Speckle noise
img_noisy = imnoise(img, 'poisson'); % Poisson noise
% Denoising
img_denoised = medfilt2(img_noisy); % Median
filtering
img_denoised = wiener2(img_noisy, [5 5]); % Wiener
filtering
img_denoised = imnlmfilt(img_noisy); % Non-local
means
img_denoised = imbilatfilt(img_noisy); % Bilateral
filtering
% Deconvolution (Deblurring)
PSF = fspecial('gaussian', [5 5], 1); % Point spread
function
img_deblurred = deconvwnr(img_blurry, PSF); % Wiener
deconvolution
img_deblurred = deconvlucy(img_blurry, PSF); % Lucy-
Richardson
img_deblurred = deconvreg(img_blurry, PSF); %
Regularized filter
```
## **10. IMAGE TRANSFORMS**
### Fourier Transform
```matlab
% FFT operations
F = fft2(img); % 2D FFT
F_shifted = fftshift(F); % Shift zero frequency
F_magnitude = abs(F_shifted); % Magnitude
spectrum
F_phase = angle(F_shifted); % Phase spectrum
F_log = log(1 + F_magnitude); % Log magnitude
% Inverse FFT
img_restored = ifft2(F); % Inverse FFT
img_restored = ifft2(ifftshift(F_shifted)); % Complete
reconstruction
% Filtering in frequency domain
[H, W] = size(img);
[u, v] = meshgrid(1:W, 1:H);
D = sqrt((u - W/2).^2 + (v - H/2).^2);
H_lowpass = double(D <= 30); % Ideal low-pass
filter
img_filtered = ifft2(ifftshift(F_shifted .* H_lowpass));
```
### Other Transforms
```matlab
% DCT transform
img_dct = dct2(img); % 2D DCT
img_idct = idct2(img_dct); % Inverse DCT
% Wavelet transforms
[LL, LH, HL, HH] = dwt2(img, 'db1'); % Discrete
wavelet
img_reconstructed = idwt2(LL, LH, HL, HH, 'db1'); % Inverse
wavelet
% Radon transform
[R, xp] = radon(img, 0:179); % Radon transform
img_iradon = iradon(R, 0:179); % Inverse Radon
% Hough transform
[H, theta, rho] = hough(img_bw); % Hough
transform
peaks = houghpeaks(H, 5); % Find peaks
lines = houghlines(img_bw, theta, rho, peaks); % Find lines
```
## **11. GEOMETRIC TRANSFORMATIONS**
### Spatial Transformations
```matlab
% Resizing
img_resized = imresize(img, 0.5); % Scale by factor
img_resized = imresize(img, [256 256]); % Target size
img_resized = imresize(img, 2, 'bicubic'); % With
interpolation
% Rotation
img_rotated = imrotate(img, 45); % Rotate 45
degrees
img_rotated = imrotate(img, 30, 'bicubic', 'crop'); % Rotate and
crop
% Cropping
img_cropped = imcrop(img); % Interactive crop
img_cropped = imcrop(img, [50 50 200 200]); % Crop
rectangle
% Translation
tform = affine2d([1 0 0; 0 1 0; 50 50 1]); % Translation
matrix
img_translated = imwarp(img, tform); % Apply
translation
% Flipping
img_flipped = flip(img, 1); % Vertical flip
img_flipped = flip(img, 2); % Horizontal flip
img_flipped = flipud(img); % Flip up-down
img_flipped = fliplr(img); % Flip left-right
```
### Advanced Geometric Operations
```matlab
% Affine transformations
tform = affine2d([2 0 0; 0 3 0; 0 0 1]); % Scaling matrix
tform = affine2d([1 0.3 0; 0.3 1 0; 0 0 1]); % Shear matrix
img_transformed = imwarp(img, tform); % Apply
transform
% Projective transformations
tform = projective2d([1 0.1 0.001; 0.1 1 0.001; 0 0 1]); % Projective
matrix
img_warped = imwarp(img, tform); % Apply
transform
% Image registration
[optimizer, metric] = imregconfig('monomodal'); %
Registration config
img_registered = imregister(img_moving, img_fixed, 'affine', optimizer,
metric);
% Polar transformations
[img_polar, r, theta] = im2polar(img); % Custom polar
transform
img_cartesian = polar2im(img_polar, size(img)); % Back to
Cartesian
```
## **12. COLOR IMAGE PROCESSING**
### Color Space Operations
```matlab
% Color channel operations
R = img_rgb(:, :, 1); % Red channel
G = img_rgb(:, :, 2); % Green channel
B = img_rgb(:, :, 3); % Blue channel
% Channel manipulation
img_rgb(:,:,1) = 0; % Remove red
img_gray = 0.2989 * R + 0.5870 * G + 0.1140 * B; % Luma
conversion
% Color adjustments
img_adjusted = imadjust(img_rgb); % Adjust each
channel
img_saturated = imsaturate(img_hsv); % Increase
saturation
% Pseudo-coloring
img_pseudo = ind2rgb(gray2ind(img_gray, 256), jet(256)); %
Apply jet colormap
img_pseudo = im2uint8(ind2rgb(gray2ind(img_gray, 64), hot(64))); %
Apply hot colormap
```
### Color Segmentation
```matlab
% Color thresholding
mask = img_rgb(:, :, 1) > 100 & img_rgb(:, :, 2) < 50 & img_rgb(:, :, 3)
< 50; % Red detection
% Color clustering
img_lab = rgb2lab(img_rgb); % Convert to
L*a*b*
ab = img_lab(:, :, 2:3); % Take a and b
channels
ab = im2single(ab); % Convert to single
[labels, centers] = imsegkmeans(ab, 3); % K-means on
color
% Color-based segmentation
L = superpixels(img_rgb, 500); % Generate
superpixels
img_seg = imsegkmeans(img_rgb, 5, 'NormalizeInput', true); %
Color-based segmentation
```
## **13. IMAGE ANALYSIS AND FEATURE EXTRACTION**
### Texture Analysis
```matlab
% GLCM features
glcm = graycomatrix(img_gray, 'Offset', [2 0]); % Gray-level
co-occurrence
stats = graycoprops(glcm, {'contrast', 'homogeneity'}); % GLCM
properties
% Local binary patterns
lbp = extractLBPFeatures(img_gray); % LBP features
% Gabor filters
g = gabor([5 10], [0 90]); % Create Gabor filter
bank
gabormag = imgaborfilt(img_gray, g); % Apply Gabor
filters
```
### Object Detection
```matlab
% Circle detection
[centers, radii] = imfindcircles(img, [20 50]); % Find circles
[centers, radii] = imfindcircles(img, [20 50], 'Sensitivity', 0.9);
% Blob detection
blobs = detectSURFFeatures(img); % SURF
features
blobs = detectMSERFeatures(img); % MSER
regions
% Template matching
C = normxcorr2(template, img); % Normalized
cross-correlation
[ypeak, xpeak] = find(C == max(C(:))); % Find peak
correlation
```
### Shape Analysis
```matlab
% Basic shape measurements
stats = regionprops(img_bw, 'Area', 'Perimeter', 'Eccentricity');
areas = [[Link]];
perimeters = [[Link]];
% Shape descriptors
circularity = 4*pi*areas ./ (perimeters.^2); % Circularity
metric
% Euler number
euler = bweuler(img_bw); % Euler number
% Convex hull
CH = bwconvhull(img_bw); % Convex hull
image
```
## **14. ADVANCED TECHNIQUES**
### Deep Learning Integration
```matlab
% Pre-trained networks
net = alexnet; % Load AlexNet
net = vgg16; % Load VGG16
net = googlenet; % Load GoogLeNet
% Image preprocessing
img_resized = imresize(img, [Link](1).InputSize(1:2)); %
Resize for network
img_normalized = im2single(img_resized); %
Normalize
% Classification
[YPred, scores] = classify(net, img_normalized); % Classify
image
% Feature extraction
layer = 'fc7'; % Feature layer
features = activations(net, img_normalized, layer); % Extract
features
```
### Image Compression
```matlab
% JPEG compression
imwrite(img, '[Link]', 'Quality', 50); % JPEG
compression
% PCA compression
img_double = im2double(img_gray); % Convert to
double
[U, S, V] = svd(img_double); % SVD
decomposition
k = 50; % Number of components
img_compressed = U(:,1:k) * S(1:k,1:k) * V(:,1:k)'; %
Compressed image
% Wavelet compression
[C, S] = wavedec2(img_gray, 3, 'db1'); % Wavelet
decomposition
C_thresh = wthresh(C, 'h', 10); % Threshold
coefficients
img_decompressed = waverec2(C_thresh, S, 'db1'); %
Reconstruct
```
### Image Quality Assessment
```matlab
% Quality metrics
psnr_val = psnr(img_restored, img_original); % Peak SNR
ssim_val = ssim(img_restored, img_original); % Structural
similarity
mse_val = immse(img_restored, img_original); % Mean
square error
nrmse = sqrt(mse_val) / (max(img_original(:)) - min(img_original(:))); %
NRMSE
% Edge preservation
edges_orig = edge(img_original, 'canny'); % Original
edges
edges_restored = edge(img_restored, 'canny'); % Restored
edges
edge_preservation = sum(edges_orig(:) & edges_restored(:)) /
sum(edges_orig(:));
```
## **15. UTILITY FUNCTIONS**
### Image Block Processing
```matlab
% Block processing
fun = @(block) std2([Link]) * ones(size([Link])); %
Function to apply
img_processed = blockproc(img, [32 32], fun); % Apply to
blocks
% Image tiling
C = im2col(img, [8 8], 'distinct'); % Convert to
columns
img_restored = col2im(C, [8 8], size(img), 'distinct'); % Convert
back
```
### Image Padding and Border Handling
```matlab
% Padding options
img_padded = padarray(img, [10 10]); % Pad with
zeros
img_padded = padarray(img, [10 10], 'symmetric'); %
Symmetric padding
img_padded = padarray(img, [10 10], 'replicate'); % Replicate
border
% Border extraction
border = impixel(img, 1:size(img,2), 1); % Top border
```
## **16. PRACTICAL EXAMPLES**
### Complete Pipeline Example
```matlab
% Complete image processing pipeline
% 1. Read image
img = imread('[Link]');
% 2. Preprocessing
if size(img, 3) == 3
img_gray = rgb2gray(img); % Convert to
grayscale
else
img_gray = img;
end
% 3. Enhancement
img_enhanced = adapthisteq(img_gray); % Adaptive
equalization
img_denoised = medfilt2(img_enhanced, [3 3]); % Noise
reduction
% 4. Segmentation
level = graythresh(img_denoised); % Otsu threshold
img_bw = imbinarize(img_denoised, level); % Binary
image
% 5. Morphological cleaning
se = strel('disk', 3);
img_clean = imopen(img_bw, se); % Remove
small objects
% 6. Feature extraction
stats = regionprops(img_clean, 'Area', 'Centroid', 'BoundingBox');
areas = [[Link]];
largest_objects = find(areas > 100); % Filter by area
% 7. Visualization
imshow(img);
hold on;
for k = 1:length(largest_objects)
rectangle('Position', stats(largest_objects(k)).BoundingBox, ...
'EdgeColor', 'r', 'LineWidth', 2);
plot(stats(largest_objects(k)).Centroid(1), ...
stats(largest_objects(k)).Centroid(2), 'b*');
end
hold off;
% 8. Save results
imwrite(img_clean, 'segmented_result.png');
save('analysis_results.mat', 'stats', 'areas');
```
### Batch Processing Example
```matlab
% Process multiple images
input_dir = 'input_images/';
output_dir = 'processed_images/';
file_list = dir(fullfile(input_dir, '*.jpg'));
for i = 1:length(file_list)
% Read image
filename = fullfile(input_dir, file_list(i).name);
img = imread(filename);
% Process
img_gray = rgb2gray(img);
img_eq = histeq(img_gray);
img_sharp = imsharpen(img_eq);
% Save
[~, name, ext] = fileparts(file_list(i).name);
output_filename = fullfile(output_dir, [name '_processed' ext]);
imwrite(img_sharp, output_filename);
fprintf('Processed: %s\n', file_list(i).name);
end
```
## **17. PERFORMANCE OPTIMIZATION**
### Memory and Speed Optimization
```matlab
% Use appropriate data types
img_uint8 = im2uint8(img_double); % Reduce
memory
% Process in blocks for large images
block_size = 1024;
for row = 1:block_size:size(img_large, 1)
for col = 1:block_size:size(img_large, 2)
block = img_large(row:min(row+block_size-1, end), ...
col:min(col+block_size-1, end));
% Process block
processed_block = medfilt2(block);
result(row:min(row+block_size-1, end), ...
col:min(col+block_size-1, end)) = processed_block;
end
end
% Pre-allocate arrays
result = zeros(size(img), 'uint8'); % Pre-allocation
```
## **18. TROUBLESHOOTING AND DEBUGGING**
### Common Issues and Solutions
```matlab
% Check for common errors
if isempty(img)
error('Image is empty');
end
if ndims(img) > 3
error('Image has more than 3 dimensions');
end
% Handle different data types
if ~isa(img, 'double')
img_double = im2double(img);
end
% Check image range
if max(img(:)) <= 1
disp('Image is in [0,1] range');
else
disp('Image is in [0,255] range');
end
```
This comprehensive guide covers MATLAB image processing from
basic to advanced levels with practical examples. Each command is
demonstrated with typical usage patterns to help you understand both
syntax and application.