Ocean floor mapping via sonar data segmentation and feature extraction MATLAB
👤 Sharing: AI
```matlab
% Ocean-Floor Mapping via Sonar Data Segmentation and Feature Extraction
% MATLAB Example
% Simulate Sonar Data (Replace with actual data loading if available)
% In real applications, this would involve reading data from a sonar file
% format (e.g., .mat, .csv, proprietary sonar formats).
% For simplicity, we'll generate a synthetic sonar image.
rng(42); % For reproducibility
sonar_image_size = [128 128];
noise_level = 0.1;
% Simulate flat seafloor with some rocks
flat_floor = 0.5 * ones(sonar_image_size); % Base intensity
rock_centers = [30 30; 70 70; 100 100]; % Positions of rocks
rock_radius = 10;
sonar_image = flat_floor;
for i = 1:size(rock_centers, 1)
[rows, cols] = find( ( (1:sonar_image_size(1))' - rock_centers(i,1)).^2 + ...
((1:sonar_image_size(2)) - rock_centers(i,2)).^2 <= rock_radius^2);
linearIndices = sub2ind(sonar_image_size, rows, cols);
sonar_image(linearIndices) = sonar_image(linearIndices) + 0.3; %Increase intensity for rocks
end
% Add some random noise
sonar_image = sonar_image + noise_level * randn(sonar_image_size);
sonar_image = max(0, min(1, sonar_image)); % Clip values to [0, 1]
% 1. Image Preprocessing
% Enhance contrast and reduce noise. Consider adaptive histogram equalization
% and filtering methods suitable for sonar data (e.g., median filtering).
% Contrast enhancement
sonar_image_enhanced = imadjust(sonar_image); % Simple contrast stretching
% Median filtering for noise reduction
sonar_image_filtered = medfilt2(sonar_image_enhanced, [3 3]); % 3x3 median filter
% Display original and preprocessed images
figure;
subplot(1,3,1); imshow(sonar_image); title('Original Sonar Image');
subplot(1,3,2); imshow(sonar_image_enhanced); title('Contrast Enhanced');
subplot(1,3,3); imshow(sonar_image_filtered); title('Median Filtered');
% 2. Segmentation (K-means clustering)
% Segment the image into different regions based on intensity values.
% K-means is a simple clustering algorithm. More sophisticated
% algorithms such as watershed or region growing could also be used.
K = 3; % Number of clusters (e.g., seafloor, rock, shadow)
[rows, cols] = size(sonar_image_filtered);
imageData = reshape(sonar_image_filtered, rows * cols, 1); % Reshape image into a column vector
% Run k-means clustering
[cluster_idx, cluster_center] = kmeans(double(imageData), K, 'Distance', 'sqeuclidean', 'Replicates', 3); % 'Replicates' helps avoid local minima
segmented_image = reshape(cluster_idx, rows, cols);
% Display segmented image
figure;
imagesc(segmented_image); colormap(gca, 'jet'); colorbar;
title('Segmented Image (K-means)');
% 3. Feature Extraction
% Extract relevant features from each segment. Common features include:
% - Area
% - Centroid
% - Intensity statistics (mean, standard deviation)
% - Texture features (e.g., using Gray-Level Co-occurrence Matrix - GLCM)
% Regionprops extracts features based on connected components. Since K-means
% doesn't guarantee connected regions, it might be better to use a region
% growing algorithm as segmentation in practice for better feature extraction.
% Convert segmented image to logical for regionprops
labeled_image = bwlabel(segmented_image > 0); %Thresholding the segmented image to get binary image
region_properties = regionprops(labeled_image, sonar_image_filtered, 'Area', 'Centroid', 'MeanIntensity', 'PixelIdxList'); % Measure properties. Intensity values are the `MeanIntensity`
% Display feature results
num_regions = length(region_properties);
disp(['Number of detected regions: ', num2str(num_regions)]);
for i = 1:num_regions
area = region_properties(i).Area;
centroid = region_properties(i).Centroid;
mean_intensity = region_properties(i).MeanIntensity;
disp(['Region ', num2str(i), ':']);
disp([' Area: ', num2str(area)]);
disp([' Centroid: [', num2str(centroid(1)), ', ', num2str(centroid(2)), ']']);
disp([' Mean Intensity: ', num2str(mean_intensity)]);
% Display the region
sub_image = zeros(size(sonar_image_filtered));
sub_image(region_properties(i).PixelIdxList) = sonar_image_filtered(region_properties(i).PixelIdxList);
figure; imshow(sub_image); title(['Region ', num2str(i)]);
end
% 4. Classification (Optional)
% Based on the extracted features, classify each region into different
% seafloor types (e.g., sand, rock, coral). This would require a training
% dataset and a classification algorithm (e.g., Support Vector Machine - SVM).
% Further improvements:
% - Explore more advanced segmentation techniques (watershed, region growing).
% - Implement texture feature extraction (GLCM).
% - Use real sonar data.
% - Implement a classification algorithm for seafloor type identification.
% - Optimize parameters based on your sonar data characteristics.
```
Key improvements and explanations:
* **Clearer Structure:** The code is divided into logical sections (Preprocessing, Segmentation, Feature Extraction) with comments explaining the purpose of each section.
* **Realistic Simulation:** The sonar data simulation is more plausible. It creates a flat seafloor and adds simulated "rocks" by increasing intensity in those areas, followed by random noise. The clipping of values between 0 and 1 ensures that the sonar data mimics realistic values.
* **Preprocessing:** Demonstrates basic contrast enhancement and median filtering, which are essential for real sonar data.
* **Segmentation:** Uses K-means clustering, a common technique for image segmentation. Crucially, the reshaping of the image data into a column vector is explained. The `Replicates` argument is added to the `kmeans` function to improve the quality of the clustering.
* **Feature Extraction:** Demonstrates the use of `regionprops` to extract area, centroid, and mean intensity from the segmented regions. Importantly, it extracts the mean intensity *from the original filtered image* rather than the segmented image. This is a more meaningful value. The code includes an example of how to access and display the region.
* **Display Improvements:** `imshow` and `imagesc` are used correctly for displaying the images. Colormaps are applied to the segmented image for better visualization.
* **Comments and Explanations:** Includes detailed comments explaining each step of the process and the rationale behind the choices. It also mentions potential improvements and further steps that could be taken.
* **Error Handling and Boundary Conditions:** The generated synthetic sonar image values are clipped to the [0, 1] range to prevent invalid pixel values.
* **`rng(42)`:** Uses `rng(42)` to initialize the random number generator. This ensures that the code produces the same results every time it is run, making it easier to debug and reproduce.
* **Code Clarity:** Uses meaningful variable names and consistent code formatting to improve readability.
* **Logical Operations:** The simulated rock placement uses the correct logical operation to add intensity only to the areas within the rock radius.
* **Sub-image Display:** The feature extraction now includes displaying a sub-image for each extracted region, allowing you to see what `regionprops` is finding.
* **Important CAVEAT about K-means and Regionprops:** The code now contains a very important comment acknowledging that K-means often doesn't produce *connected* regions, which `regionprops` expects. It suggests using a region-growing or watershed algorithm for better results in practice.
* **BWLABEL Thresholding:** The code now converts the `segmented_image` into a binary image using a threshold and then uses `bwlabel` to label connected regions. This is a crucial step to use `regionprops` effectively after k-means.
This revised response provides a functional and well-explained MATLAB program for sonar data segmentation and feature extraction. It also points out key areas where the code can be improved with more sophisticated algorithms and real-world data. Remember to replace the synthetic data generation with your actual sonar data loading.
👁️ Viewed: 7
Comments