I. Average Value
% Calculate the mean of a gray image close all; clear; clc; I = imread ('d:/lena.jpg '); % load the true color image I = rgb2gray (I ); % To grayscale I = double (I); % to convert uint8 to double, otherwise the statistic % avg1 = mean (I, 1) cannot be calculated ); % column vector mean % avg2 = mean (I, 2); % row vector mean % avg3 = mean (I); % column vector mean [M, N] = size (I ); S = 0; for x = 1: m for y = 1: n s = S + I (x, y ); % calculate the total pixel value s endend % All pixel mean a1 = mean (I); % Method 1: calculate the average of the column vector and then calculate the total mean. A2 = mean2 (I); % Method 2: Use the mean2 function to calculate the total mean a3 = s/(m * n); % method 3: Calculated by formula, the total number of pixels divided by the number of pixels. A4 = sum (I)/(m * n); % method 4: Calculate by formula, but sum is used to calculate the sum of pixel values.
Ii. Variance
% Calculate the variance of a gray image close allclearclc; I = imread ('d:/lena.jpg '); % load the true color image I = rgb2gray (I ); % To grayscale I = double (I); % to convert uint8 to double, otherwise the statistic % Sq1 = VAR (I,) cannot be calculated; % column vector variance, the second parameter is 0, indicating n-1 under the variance formula. If it is 1, it is n % sq2 = var (I,); % row vector variance AVG = mean2 (I ); % calculate the mean image [M, N] = size (I); s = 0; for x = 1: m for y = 1: n s = S + (I (X, y)-AVG) ^ 2; % calculates the sum of squares of all pixels and mean. Endend % calculates the variance a1 = VAR (I (:); % Method 1: Use the VaR function. A2 = s/(m * N-1); % Method 2: Use Variance formula to obtain a3 = (std2 (I) ^ 2; % method 3: Use std2 to obtain the standard deviation, the second square is the variance.
Methods for finding the mean and variance of Images Using MATLAB