Madcracke

Untitled

Jan 20th, 2025
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 26.64 KB | Source Code | 0 0
  1. 1....Binary Threshold...
  2.  
  3. % Main script to read an image, convert it to binary, and display the result
  4. % altime using gray image
  5. img = imread('ccc.jpg');
  6. % Call convert2binary() function to convert the image to binary
  7. binary_image = convert2binary(img);
  8. % Function to convert an image to binary based on thresholding
  9. function [binary] = convert2binary(img)
  10.     [x, y, z] = size(img);
  11.     % If the input is an RGB image, convert it to grayscale
  12.     if z == 3
  13.         img = 0.2989 * img(:,:,1) + 0.5870 * img(:,:,2) + 0.1140 * img(:,:,3); % Manual grayscale conversion
  14.     end
  15.     % Convert image class from 'uint8' to 'double'
  16.     img = double(img);
  17.     % Calculate the sum of all gray level pixel values
  18.     total_sum = sum(img(:));
  19.     % Calculate threshold as the average pixel value
  20.     threshold = total_sum / (x * y);
  21.     % Initialize the binary image matrix
  22.     binary = zeros(x, y);
  23.     % Apply thresholding
  24.     for i = 1:x
  25.         for j = 1:y
  26.             if img(i, j) >= threshold
  27.                 binary(i, j) = 1;
  28.             else
  29.                 binary(i, j) = 0;
  30.             end
  31.         end
  32.     end
  33. end
  34. figure;
  35. subplot(1, 2, 1);
  36. imshow(img);
  37. title('Original Image');
  38. subplot(1, 2, 2);
  39. imshow(binary_image);
  40. title('Binary Image');
  41.  
  42. 2....Contrast...
  43.  
  44. % Load the image
  45. img = imread('color.jpg');  % Replace with the name of your image file
  46.  
  47. % Convert the image to grayscale (if not already)
  48. gray_img = rgb2gray(img);
  49.  
  50. % Get the minimum and maximum pixel values of the grayscale image
  51. r_min = double(min(gray_img(:)));  % Minimum pixel value
  52. r_max = double(max(gray_img(:)));  % Maximum pixel value
  53.  
  54. % Set the desired output range
  55. s_min = 0;  % Minimum output pixel value
  56. s_max = 255;  % Maximum output pixel value
  57.  
  58. % Apply contrast stretching
  59. contrast_stretched_img = uint8((double(gray_img) - r_min) / (r_max - r_min) * (s_max - s_min) + s_min);
  60.  
  61. % Display the original and contrast stretched images
  62. figure;
  63. subplot(1, 2, 1);
  64. imshow(gray_img);
  65. title('Original Image');
  66.  
  67. subplot(1, 2, 2);
  68. imshow(contrast_stretched_img);
  69. title('Contrast Stretched Image');
  70.  
  71. 3.....Feature extraction...
  72.  
  73. clc; clear; close all;
  74.  
  75. % Step 1: Read the color image
  76. image = imread('apple.jpeg');  % Replace with your image file path
  77.  
  78. % Step 2: Extract RGB components
  79. red_component = image(:,:,1);    % Red component (1st channel)
  80. green_component = image(:,:,2);  % Green component (2nd channel)
  81. blue_component = image(:,:,3);   % Blue component (3rd channel)
  82.  
  83. % Step 3: Manually convert to grayscale using the formula
  84. gray_image_manual = 0.2989 * double(red_component) + 0.5870 * double(green_component) + 0.1140 * double(blue_component);
  85. gray_image_manual = uint8(gray_image_manual);  % Convert back to uint8 for display
  86.  
  87. % Step 4: Display the original and component images
  88. figure;
  89.  
  90. % Original Image
  91. subplot(2,3,1);
  92. imshow(image);
  93. title('Original Color Image');
  94.  
  95. % Red Component
  96. subplot(2,3,2);
  97. imshow(red_component);
  98. title('Red Component');
  99.  
  100. % Green Component
  101. subplot(2,3,3);
  102. imshow(green_component);
  103. title('Green Component');
  104.  
  105. % Blue Component
  106. subplot(2,3,4);
  107. imshow(blue_component);
  108. title('Blue Component');
  109.  
  110. % Grayscale Image (Manually Converted)
  111. subplot(2,3,5);
  112. imshow(gray_image_manual);
  113. title('Grayscale Image (Manual Conversion)');
  114.  
  115. 4....Histogram....
  116.  
  117. % Load the image
  118. image = imread('lab practise/apple.jpeg'); % Replace 'your_image.jpg' with the actual image path
  119.  
  120. % Check if the image is grayscale or RGB
  121. if size(image, 3) == 1
  122.     % For Grayscale image
  123.     figure;
  124.     histogram(image, 256); % 256 bins for pixel intensity
  125.     title('Histogram of Grayscale Image');
  126.     xlabel('Pixel Intensity');
  127.     ylabel('Frequency');
  128. else
  129.     % For RGB image
  130.     redChannel = image(:,:,1); % Red channel
  131.     greenChannel = image(:,:,2); % Green channel
  132.     blueChannel = image(:,:,3); % Blue channel
  133.    
  134.     % Plot histograms for each channel
  135.     figure;
  136.     subplot(3, 1, 1);
  137.     histogram(redChannel, 256, 'FaceColor', 'r');
  138.     title('Red Channel Histogram');
  139.     xlabel('Pixel Intensity');
  140.     ylabel('Frequency');
  141.    
  142.     subplot(3, 1, 2);
  143.     histogram(greenChannel, 256, 'FaceColor', 'g');
  144.     title('Green Channel Histogram');
  145.     xlabel('Pixel Intensity');
  146.     ylabel('Frequency');
  147.    
  148.     subplot(3, 1, 3);
  149.     histogram(blueChannel, 256, 'FaceColor', 'b');
  150.     title('Blue Channel Histogram');
  151.     xlabel('Pixel Intensity');
  152.     ylabel('Frequency');
  153. end
  154.  
  155.  
  156. 5....Negative...
  157.  
  158. % Load the image
  159. img = imread('flower.jpg'); % Replace 'negativeim.jpeg' with your image file name
  160.  
  161. % Convert the image to double precision to prevent data loss during inversion
  162. img = double(img);
  163.  
  164. % Maximum pixel value for an 8-bit image
  165. L = 255;
  166.  
  167. % Generate the negative image by applying the equation s = L - 1 - r
  168. negative_img = L - 1 - img;
  169.  
  170. % Convert back to uint8 for display
  171. negative_img = uint8(negative_img);
  172.  
  173. % Display the original and negative images
  174. figure;
  175. subplot(1, 2, 1);
  176. imshow(uint8(img)); % Display the original image
  177. title('Original Image');
  178.  
  179. subplot(1, 2, 2);
  180. imshow(negative_img); % Display the negative image
  181. title('Negative Image');
  182.  
  183. 6....rgb2gray...
  184.  
  185. % Read the RGB image
  186. image = imread('color.jpg');
  187.  
  188. % Separate the color channels
  189. R = image(:, :, 1);
  190. G = image(:, :, 2);
  191. B = image(:, :, 3);
  192.  
  193. % Convert RGB to grayscale
  194. grayImage = uint8(0.2989 * double(R) + 0.5870 * double(G) + 0.1140 * double(B));
  195.  
  196. % Convert grayscale back to RGB by replicating grayscale values across R, G, and B channels
  197. rgbImage = cat(3, R, G, B);
  198.  
  199. % Display images
  200. figure;
  201. subplot(2, 3, 1), imshow(image), title('Original RGB Image');
  202. subplot(2, 3, 2), imshow(R), title('Red Channel');
  203. subplot(2, 3, 3), imshow(G), title('Green Channel');
  204. subplot(2, 3, 4), imshow(B), title('Blue Channel');
  205. subplot(2, 3, 5), imshow(grayImage), title('Grayscale Image');
  206. subplot(2, 3, 6), imshow(rgbImage), title('Reconstructed RGB Image');
  207.  
  208. ....Robert+sobel+prewitt....
  209. % Read and convert the input image to grayscale
  210. inputImage = imread('ccc.jpg'); % Replace with your image file
  211. grayImage = rgb2gray(inputImage);       % Convert to grayscale if it's a color image
  212. grayImage = double(grayImage);          % Convert to double for computation
  213.  
  214. % Initialize the size of the image
  215. [rows, cols] = size(grayImage);
  216.  
  217. % Define the kernels
  218. RobertX = [1 0; 0 -1];  % Robert Cross gradient kernel (X direction)
  219. RobertY = [0 1; -1 0];  % Robert Cross gradient kernel (Y direction)
  220.  
  221. PrewittX = [-1 0 1; -1 0 1; -1 0 1];  % Prewitt kernel (X direction)
  222. PrewittY = [-1 -1 -1; 0 0 0; 1 1 1];  % Prewitt kernel (Y direction)
  223.  
  224. SobelX = [-1 0 1; -2 0 2; -1 0 1];    % Sobel kernel (X direction)
  225. SobelY = [-1 -2 -1; 0 0 0; 1 2 1];    % Sobel kernel (Y direction)
  226.  
  227. % Initialize the gradient magnitude images
  228. RobertEdge = zeros(rows, cols);
  229. PrewittEdge = zeros(rows, cols);
  230. SobelEdge = zeros(rows, cols);
  231.  
  232. % Apply the Robert Operator (X and Y gradients)
  233. for i = 1:rows-1
  234.     for j = 1:cols-1
  235.         % Apply Robert X kernel
  236.         GxR = sum(sum(grayImage(i:i+1, j:j+1) .* RobertX));
  237.         % Apply Robert Y kernel
  238.         GyR = sum(sum(grayImage(i:i+1, j:j+1) .* RobertY));
  239.         % Compute gradient magnitude
  240.         RobertEdge(i,j) = sqrt(GxR^2 + GyR^2);
  241.     end
  242. end
  243.  
  244. % Apply the Prewitt Operator (X and Y gradients)
  245. for i = 2:rows-1
  246.     for j = 2:cols-1
  247.         % Apply Prewitt X kernel
  248.         GxP = sum(sum(grayImage(i-1:i+1, j-1:j+1) .* PrewittX));
  249.         % Apply Prewitt Y kernel
  250.         GyP = sum(sum(grayImage(i-1:i+1, j-1:j+1) .* PrewittY));
  251.         % Compute gradient magnitude
  252.         PrewittEdge(i,j) = sqrt(GxP^2 + GyP^2);
  253.     end
  254. end
  255.  
  256. % Apply the Sobel Operator (X and Y gradients)
  257. for i = 2:rows-1
  258.     for j = 2:cols-1
  259.         % Apply Sobel X kernel
  260.         GxS = sum(sum(grayImage(i-1:i+1, j-1:j+1) .* SobelX));
  261.         % Apply Sobel Y kernel
  262.         GyS = sum(sum(grayImage(i-1:i+1, j-1:j+1) .* SobelY));
  263.         % Compute gradient magnitude
  264.         SobelEdge(i,j) = sqrt(GxS^2 + GyS^2);
  265.     end
  266. end
  267.  
  268. % Normalize the results to display correctly
  269. RobertEdge = uint8(RobertEdge / max(RobertEdge(:)) * 255);
  270. PrewittEdge = uint8(PrewittEdge / max(PrewittEdge(:)) * 255);
  271. SobelEdge = uint8(SobelEdge / max(SobelEdge(:)) * 255);
  272.  
  273. % Display the results
  274. figure;
  275. subplot(2,2,1); imshow(uint8(grayImage)); title('Original Image');
  276. subplot(2,2,2); imshow(RobertEdge); title('Robert Edge Detection');
  277. subplot(2,2,3); imshow(PrewittEdge); title('Prewitt Edge Detection');
  278. subplot(2,2,4); imshow(SobelEdge); title('Sobel Edge Detection');
  279.  
  280.  
  281. 7....imagee Sharpen...
  282.  
  283. function main()
  284.     % Load an example grayscale image
  285.     image = imread('F:\MATLAB_DIP\labgray.jpg'); % Replace with path to your image
  286.     if size(image, 3) == 3
  287.         image = rgb_to_grayscale(image); % Convert to grayscale if it's an RGB image
  288.     end
  289.  
  290.     % Apply smoothing
  291.     smoothed_image = smooth_image(image);
  292.  
  293.     % Apply sharpening
  294.     sharpened_image = sharpen_image(image);
  295.  
  296.     % Display original, smoothed, and sharpened images
  297.     figure;
  298.     subplot(1, 3, 1);
  299.     imshow(image);
  300.     title('Original Image');
  301.  
  302.     subplot(1, 3, 2);
  303.     imshow(smoothed_image);
  304.     title('Smoothed Image');
  305.  
  306.     subplot(1, 3, 3);
  307.     imshow(sharpened_image);
  308.     title('Sharpened Image');
  309. end
  310.  
  311. function grayscale_image = rgb_to_grayscale(rgb_image)
  312.     % Convert RGB image to grayscale without built-in function
  313.     [height, width, ~] = size(rgb_image);
  314.     grayscale_image = zeros(height, width, 'uint8');
  315.     for i = 1:height
  316.         for j = 1:width
  317.             R = double(rgb_image(i, j, 1));
  318.             G = double(rgb_image(i, j, 2));
  319.             B = double(rgb_image(i, j, 3));
  320.             grayscale_image(i, j) = uint8(0.2989 * R + 0.5870 * G + 0.1140 * B);
  321.         end
  322.     end
  323. end
  324.  
  325. function smoothed_image = smooth_image(image)
  326.     % Define a Gaussian kernel for smoothing (3x3)
  327.     kernel = [1, 2, 1;
  328.               2, 4, 2;
  329.               1, 2, 1];
  330.     kernel = kernel / sum(kernel(:)); % Normalize the kernel
  331.  
  332.     % Get image dimensions
  333.     [height, width] = size(image);
  334.  
  335.     % Initialize output image
  336.     smoothed_image = zeros(height, width, 'uint8');
  337.  
  338.     % Apply convolution without using built-in function
  339.     for i = 2:height-1
  340.         for j = 2:width-1
  341.             % Extract 3x3 region
  342.             region = double(image(i-1:i+1, j-1:j+1));
  343.             % Apply kernel
  344.             smoothed_value = sum(sum(region .* kernel));
  345.             smoothed_image(i, j) = uint8(smoothed_value);
  346.         end
  347.     end
  348. end
  349.  
  350. function sharpened_image = sharpen_image(image)
  351.     % Define a sharpening kernel (Laplacian kernel for edge enhancement)
  352.     kernel = [0, -1, 0;
  353.              -1, 5, -1;
  354.               0, -1, 0];
  355.  
  356.     % Get image dimensions
  357.     [height, width] = size(image);
  358.  
  359.     % Initialize output image
  360.     sharpened_image = zeros(height, width, 'uint8');
  361.  
  362.     % Apply convolution without using built-in function
  363.     for i = 2:height-1
  364.         for j = 2:width-1
  365.             % Extract 3x3 region
  366.             region = double(image(i-1:i+1, j-1:j+1));
  367.             % Apply kernel
  368.             sharpened_value = sum(sum(region .* kernel));
  369.             % Ensure pixel value is within 0-255 range
  370.             sharpened_image(i, j) = uint8(min(max(sharpened_value, 0), 255));
  371.         end
  372.     end
  373. end
  374.  
  375. 8.....Region splitting and merging......
  376.  
  377.  
  378. % Read and convert the image to grayscale
  379. inputImage = imread('input_image.jpg');  % Replace with your image file
  380. grayImage = rgb2gray(inputImage);        % Convert to grayscale if the image is color
  381. grayImage = double(grayImage);           % Convert to double for computation
  382.  
  383. % Parameters
  384. threshold = 50;                          % Threshold for splitting/merging criterion (variance threshold)
  385. minRegionSize = 8;                       % Minimum region size for merging (in pixels)
  386. maxRegionSize = 100;                     % Maximum size to prevent splitting too much
  387. splitThreshold = 10;                     % Variance threshold for splitting a region
  388. regionMap = zeros(size(grayImage));      % Initialize region map
  389.  
  390. % Image dimensions
  391. [rows, cols] = size(grayImage);
  392.  
  393. % Function to split and merge a region based on variance
  394. function regionMap = splitMerge(image, regionMap, threshold, x, y, width, height)
  395.     % Calculate the mean and variance of the region
  396.     region = image(x:x+width-1, y:y+height-1);
  397.     regionMean = mean(region(:));
  398.     regionVar = var(region(:));
  399.    
  400.     % If variance exceeds the threshold and region is large enough, split further
  401.     if regionVar > threshold && width > 2 && height > 2
  402.         midX = floor(width / 2);
  403.         midY = floor(height / 2);
  404.        
  405.         % Split region into 4 smaller sub-regions and recursively apply splitMerge
  406.         regionMap = splitMerge(image, regionMap, threshold, x, y, midX, midY);                    % Top-left
  407.         regionMap = splitMerge(image, regionMap, threshold, x, y + midY, midX, height - midY);     % Top-right
  408.         regionMap = splitMerge(image, regionMap, threshold, x + midX, y, width - midX, midY);       % Bottom-left
  409.         regionMap = splitMerge(image, regionMap, threshold, x + midX, y + midY, width - midX, height - midY);  % Bottom-right
  410.     else
  411.         % Mark the region as homogeneous
  412.         regionMap(x:x+width-1, y:y+height-1) = 1;
  413.     end
  414. end
  415.  
  416. % Start region splitting from the full image
  417. regionMap = splitMerge(grayImage, regionMap, splitThreshold, 1, 1, rows, cols);
  418.  
  419. % Merge small regions if their means are similar
  420. for i = 1:rows-1
  421.     for j = 1:cols-1
  422.         if regionMap(i, j) == 1 && regionMap(i+1, j) == 1 && regionMap(i, j+1) == 1
  423.             % Merge neighboring similar regions based on pixel intensity values
  424.             if abs(grayImage(i, j) - grayImage(i+1, j)) < threshold && abs(grayImage(i, j) - grayImage(i, j+1)) < threshold
  425.                 regionMap(i, j) = 1;  % Mark as edge-free
  426.             end
  427.         end
  428.     end
  429. end
  430.  
  431. % Create the final edge-detection result
  432. edgeImage = zeros(size(grayImage));
  433.  
  434. % Mark boundaries of regions as edges
  435. for i = 2:rows-1
  436.     for j = 2:cols-1
  437.         if regionMap(i, j) ~= regionMap(i-1, j) || regionMap(i, j) ~= regionMap(i, j-1)
  438.             edgeImage(i, j) = 255;  % Mark as boundary (edge)
  439.         else
  440.             edgeImage(i, j) = 0;    % Inside homogeneous regions
  441.         end
  442.     end
  443. end
  444.  
  445. % Display the original image and edge-detection result
  446. figure;
  447. subplot(1,2,1); imshow(uint8(grayImage)); title('Original Image');
  448. subplot(1,2,2); imshow(uint8(edgeImage)); title('Region Splitting and Merging Edge Detection');
  449.  
  450. 9.....Region Growing.......
  451.  
  452. % Read the image and convert to grayscale
  453. inputImage = imread('can1.jpg'); % Replace with your image file
  454. grayImage = rgb2gray(inputImage);       % Convert to grayscale if the image is in color
  455. grayImage = double(grayImage);          % Convert to double for computation
  456.  
  457. % Initialize parameters
  458. threshold = 20;                         % Threshold for similarity
  459. seedX = 100;                            % Seed X coordinate
  460. seedY = 100;                            % Seed Y coordinate
  461. [rows, cols] = size(grayImage);         % Get the size of the image
  462. visited = false(rows, cols);            % Create a matrix to mark visited pixels
  463. edgeImage = zeros(rows, cols);         % Initialize the edge image
  464.  
  465. % Initialize region with the seed pixel
  466. region = zeros(rows, cols);
  467. region(seedX, seedY) = 1;              % Mark the seed point
  468.  
  469. % Grow region starting from the seed point
  470. while true
  471.     changes = false;  % Flag to check if any new pixels were added
  472.  
  473.     % Loop through all pixels to expand region
  474.     for i = 2:rows-1
  475.         for j = 2:cols-1
  476.             if region(i, j) == 1 && ~visited(i, j)
  477.                 visited(i, j) = true; % Mark the pixel as visited
  478.                
  479.                 % Check all 8 neighbors
  480.                 for dx = -1:1
  481.                     for dy = -1:1
  482.                         nx = i + dx;
  483.                         ny = j + dy;
  484.                        
  485.                         % Make sure the new coordinates are within bounds
  486.                         if nx > 0 && ny > 0 && nx <= rows && ny <= cols
  487.                             % If the neighbor is similar to the current region, add it
  488.                             if abs(grayImage(nx, ny) - grayImage(i, j)) < threshold && region(nx, ny) == 0
  489.                                 region(nx, ny) = 1;
  490.                                 changes = true; % New pixel added to the region
  491.                             end
  492.                         end
  493.                     end
  494.                 end
  495.             end
  496.         end
  497.     end
  498.    
  499.     % Stop the process if no new pixels were added in the last iteration
  500.     if ~changes
  501.         break;
  502.     end
  503. end
  504.  
  505. % Create the edge image by marking boundaries
  506. for i = 2:rows-1
  507.     for j = 2:cols-1
  508.         if region(i, j) == 1
  509.             edgeImage(i, j) = 255; % Region boundary is marked as white
  510.         else
  511.             edgeImage(i, j) = 0;   % Non-region areas are marked as black
  512.         end
  513.     end
  514. end
  515.  
  516. % Display the results
  517. figure;
  518. subplot(1,2,1); imshow(uint8(grayImage)); title('Original Image');
  519. subplot(1,2,2); imshow(uint8(edgeImage)); title('Region Growing Edge Detection');
  520.  
  521.  
  522. 10.....Canny....
  523.  
  524.  
  525. % Read the input image
  526. inputImage = imread('can1.jpg'); % Replace with your image file
  527. inputImage = rgb2gray(inputImage);      % Convert to grayscale if it's a color image
  528.  
  529. % Convert the image to double for computations
  530. inputImage = double(inputImage);
  531.  
  532. % Step 1: Apply Gaussian filter to smooth the image
  533. % Define a 5x5 Gaussian filter
  534. sigma = 1.4; % Standard deviation
  535. filterSize = 5;
  536. [x, y] = meshgrid(-floor(filterSize/2):floor(filterSize/2));
  537. gaussianFilter = exp(-(x.^2 + y.^2) / (2 * sigma^2));
  538. gaussianFilter = gaussianFilter / sum(gaussianFilter(:)); % Normalize
  539.  
  540. % Convolve the image with the Gaussian filter
  541. [rows, cols] = size(inputImage);
  542. smoothedImage = zeros(rows, cols);
  543. for i = 3:rows-2
  544.     for j = 3:cols-2
  545.         region = inputImage(i-2:i+2, j-2:j+2);
  546.         smoothedImage(i, j) = sum(sum(region .* gaussianFilter));
  547.     end
  548. end
  549.  
  550. % Step 2: Compute gradients using Sobel operator
  551. Gx = [-1 0 1; -2 0 2; -1 0 1]; % Sobel x-direction kernel
  552. Gy = [-1 -2 -1; 0 0 0; 1 2 1]; % Sobel y-direction kernel
  553.  
  554. gradientX = zeros(rows, cols);
  555. gradientY = zeros(rows, cols);
  556.  
  557. for i = 2:rows-1
  558.     for j = 2:cols-1
  559.         region = smoothedImage(i-1:i+1, j-1:j+1);
  560.         gradientX(i, j) = sum(sum(region .* Gx));
  561.         gradientY(i, j) = sum(sum(region .* Gy));
  562.     end
  563. end
  564.  
  565. % Compute gradient magnitude and direction
  566. gradientMagnitude = sqrt(gradientX.^2 + gradientY.^2);
  567. gradientDirection = atan2d(gradientY, gradientX); % Direction in degrees
  568.  
  569. % Normalize gradient magnitude to 0-255
  570. gradientMagnitude = gradientMagnitude / max(gradientMagnitude(:)) * 255;
  571.  
  572. % Step 3: Non-maximum suppression
  573. nmsImage = zeros(rows, cols);
  574. angle = mod(gradientDirection, 180); % Convert to 0-180 degrees
  575. for i = 2:rows-1
  576.     for j = 2:cols-1
  577.         % Determine the neighboring pixels to compare
  578.         if (angle(i, j) >= 0 && angle(i, j) < 22.5) || (angle(i, j) >= 157.5 && angle(i, j) <= 180)
  579.             neighbor1 = gradientMagnitude(i, j-1);
  580.             neighbor2 = gradientMagnitude(i, j+1);
  581.         elseif (angle(i, j) >= 22.5 && angle(i, j) < 67.5)
  582.             neighbor1 = gradientMagnitude(i-1, j+1);
  583.             neighbor2 = gradientMagnitude(i+1, j-1);
  584.         elseif (angle(i, j) >= 67.5 && angle(i, j) < 112.5)
  585.             neighbor1 = gradientMagnitude(i-1, j);
  586.             neighbor2 = gradientMagnitude(i+1, j);
  587.         else
  588.             neighbor1 = gradientMagnitude(i-1, j-1);
  589.             neighbor2 = gradientMagnitude(i+1, j+1);
  590.         end
  591.        
  592.         % Suppress non-maximum pixels
  593.         if gradientMagnitude(i, j) >= neighbor1 && gradientMagnitude(i, j) >= neighbor2
  594.             nmsImage(i, j) = gradientMagnitude(i, j);
  595.         else
  596.             nmsImage(i, j) = 0;
  597.         end
  598.     end
  599. end
  600.  
  601. % Step 4: Double threshold and edge tracking by hysteresis
  602. highThreshold = 40; % High threshold (adjust as needed)
  603. lowThreshold = 20;  % Low threshold (adjust as needed)
  604.  
  605. strongEdges = nmsImage > highThreshold;
  606. weakEdges = nmsImage > lowThreshold & nmsImage <= highThreshold;
  607.  
  608. % Edge tracking by hysteresis
  609. finalEdges = strongEdges;
  610. for i = 2:rows-1
  611.     for j = 2:cols-1
  612.         if weakEdges(i, j)
  613.             % Check if any strong edge is in the neighborhood
  614.             if any(any(strongEdges(i-1:i+1, j-1:j+1)))
  615.                 finalEdges(i, j) = 1;
  616.             end
  617.         end
  618.     end
  619. end
  620.  
  621. % Display the results
  622. figure;
  623. subplot(2, 2, 1); imshow(uint8(inputImage)); title('Original Image');
  624. subplot(2, 2, 2); imshow(uint8(smoothedImage)); title('Smoothed Image');
  625. subplot(2, 2, 3); imshow(uint8(nmsImage)); title('Non-Maximum Suppressed');
  626. subplot(2, 2, 4); imshow(finalEdges); title('Final Edge Detected Image');
  627.  
  628. 11....OTSu....
  629.  
  630.  
  631. % Read the input image
  632. inputImage = imread('can8.jpeg'); % Replace with your image file
  633. inputImage = rgb2gray(inputImage);      % Convert to grayscale if it's a color image
  634.  
  635. % Convert the image to double for computations
  636. inputImage = double(inputImage);
  637.  
  638. % Step 1: Compute Gradient Magnitude using Sobel Operator
  639. % Define Sobel Kernels
  640. Gx = [-1 0 1; -2 0 2; -1 0 1];
  641. Gy = [-1 -2 -1; 0 0 0; 1 2 1];
  642.  
  643. % Initialize gradient matrices
  644. [rows, cols] = size(inputImage);
  645. gradientX = zeros(rows, cols);
  646. gradientY = zeros(rows, cols);
  647.  
  648. % Apply Sobel Operator
  649. for i = 2:rows-1
  650.     for j = 2:cols-1
  651.         region = inputImage(i-1:i+1, j-1:j+1);
  652.         gradientX(i, j) = sum(sum(region .* Gx));
  653.         gradientY(i, j) = sum(sum(region .* Gy));
  654.     end
  655. end
  656.  
  657. % Compute Gradient Magnitude
  658. gradientMagnitude = sqrt(gradientX.^2 + gradientY.^2);
  659.  
  660. % Normalize gradient magnitude to 0-255
  661. gradientMagnitude = gradientMagnitude / max(gradientMagnitude(:)) * 255;
  662.  
  663. % Step 2: Implement OTSU's Method for Thresholding
  664. % Flatten the gradient magnitude image into a histogram
  665. histogram = zeros(256, 1); % Initialize histogram for pixel values [0-255]
  666.  
  667. % Compute the histogram
  668. for value = 0:255
  669.     histogram(value + 1) = sum(gradientMagnitude(:) == value);
  670. end
  671.  
  672. % Compute total weight and mean
  673. totalPixels = sum(histogram);
  674. totalMean = sum((0:255) .* histogram') / totalPixels;
  675.  
  676. % Initialize variables for OTSU
  677. maxVariance = 0;
  678. optimalThreshold = 0;
  679.  
  680. % Iterate through all possible thresholds
  681. weightBackground = 0;
  682. meanBackground = 0;
  683.  
  684. for threshold = 0:255
  685.     weightBackground = weightBackground + histogram(threshold + 1);
  686.     if weightBackground == 0
  687.         continue;
  688.     end
  689.     weightForeground = totalPixels - weightBackground;
  690.     if weightForeground == 0
  691.         break;
  692.     end
  693.  
  694.     meanBackground = meanBackground + threshold * histogram(threshold + 1);
  695.     currentMeanBackground = meanBackground / weightBackground;
  696.     currentMeanForeground = (totalMean - meanBackground) / weightForeground;
  697.  
  698.     % Compute Between-Class Variance
  699.     betweenClassVariance = weightBackground * weightForeground * ...
  700.         (currentMeanBackground - currentMeanForeground)^2;
  701.  
  702.     % Update maximum variance and optimal threshold
  703.     if betweenClassVariance > maxVariance
  704.         maxVariance = betweenClassVariance;
  705.         optimalThreshold = threshold;
  706.     end
  707. end
  708.  
  709. % Step 3: Threshold the Gradient Magnitude
  710. binaryEdgeImage = gradientMagnitude > optimalThreshold;
  711.  
  712. % Display the Results
  713. figure;
  714. subplot(1, 3, 1); imshow(uint8(inputImage)); title('Original Image');
  715. subplot(1, 3, 2); imshow(uint8(gradientMagnitude)); title('Gradient Magnitude');
  716. subplot(1, 3, 3); imshow(binaryEdgeImage); title('Edge Detected Image (OTSU)');
  717.  
  718. 12....Background subtraction......
  719.  
  720. % Background Subtraction in MATLAB
  721.  
  722. % Read the background image
  723. background = imread('otsu.jpg');
  724. background = rgb2gray(background); % Convert to grayscale if it's RGB
  725.  
  726. % Read the current frame (e.g., from a video or an image)
  727. current_frame = imread('graynegative.jpg');
  728. current_frame = rgb2gray(current_frame); % Convert to grayscale if it's RGB
  729.  
  730. % Convert images to double precision for subtraction
  731. background = double(background);
  732. current_frame = double(current_frame);
  733.  
  734. % Perform background subtraction
  735. difference = abs(current_frame - background);
  736.  
  737. % Thresholding the difference to identify foreground objects
  738. threshold = 30; % Adjust based on your needs
  739. foreground = difference > threshold;
  740.  
  741. % Display the original, background, and background-subtracted images
  742. subplot(1, 3, 1);
  743. imshow(uint8(background));
  744. title('Background');
  745.  
  746. subplot(1, 3, 2);
  747. imshow(uint8(current_frame));
  748. title('Current Frame');
  749.  
  750. subplot(1, 3, 3);
  751. imshow(foreground);
  752. title('Background Subtracted Image');
  753.  
  754. % Optional: Save the result
  755. imwrite(foreground, 'background_subtracted_image.jpg');
  756.  
  757. ......filter noise enhance....
  758.  
  759. % Load an image
  760. originalImage = imread('pepper.jpg'); % Load your image file
  761. if size(originalImage, 3) == 3
  762.     originalImage = rgb2gray(originalImage); % Convert to grayscale for simplicity
  763. end
  764.  
  765. % Resize the image for faster processing
  766. originalImage = imresize(originalImage, [256, 256]);
  767.  
  768. % Display original image
  769. figure;
  770. subplot(3, 3, 1);
  771. imshow(originalImage);
  772. title('Original Image');
  773.  
  774. % Apply different types of noise
  775. noisyImages = {};
  776. noiseTypes = {'gaussian', 'salt & pepper', 'speckle'};
  777.  
  778. for i = 1:length(noiseTypes)
  779.     noisyImages{i} = imnoise(originalImage, noiseTypes{i});
  780.     subplot(3, 3, i+1);
  781.     imshow(noisyImages{i});
  782.     title([noiseTypes{i}, ' Noise']);
  783. end
  784.  
  785. % Restore/enhance the noisy images using different filters
  786. restoredImages = {};
  787. filterMethods = {'Gaussian', 'Median', 'Wiener'};
  788. PSNRValues = zeros(length(noiseTypes), length(filterMethods)); % For performance comparison
  789.  
  790. for i = 1:length(noiseTypes)
  791.     for j = 1:length(filterMethods)
  792.         switch filterMethods{j}
  793.             case 'Gaussian'
  794.                 h = fspecial('gaussian', [3, 3], 0.5);
  795.                 restoredImages{i, j} = imfilter(noisyImages{i}, h, 'replicate');
  796.             case 'Median'
  797.                 restoredImages{i, j} = medfilt2(noisyImages{i}, [3, 3]);
  798.             case 'Wiener'
  799.                 restoredImages{i, j} = wiener2(noisyImages{i}, [5, 5]);
  800.         end
  801.         % Compute PSNR for performance evaluation
  802.         PSNRValues(i, j) = psnr(restoredImages{i, j}, originalImage);
  803.     end
  804. end
  805.  
  806. % Display restored images and PSNR values
  807. figure;
  808. for i = 1:length(noiseTypes)
  809.     for j = 1:length(filterMethods)
  810.         subplot(length(noiseTypes), length(filterMethods), (i-1)*length(filterMethods) + j);
  811.         imshow(restoredImages{i, j});
  812.         title(sprintf('%s Filter\n(PSNR: %.2f dB)', filterMethods{j}, PSNRValues(i, j)));
  813.     end
  814. end
  815.  
  816. % Print PSNR values
  817. disp('PSNR Values (dB):');
  818. disp(array2table(PSNRValues, 'VariableNames', filterMethods, 'RowNames', noiseTypes));
  819.  
  820.  
  821.  
  822.  
Advertisement
Add Comment
Please, Sign In to add comment