Chapter 2 Grayscale Transformation and Spatial Filtering

Chapter 2 Grayscale Transformation and Spatial Filtering

  • Grayscale transformation function
    • Functions imadjust and stretchlim
    • Contrast and Contrast Stretch Transforms
    • Specify an arbitrary grayscale transformation
    • Practical M-function
  • Histogram Processing and Function Plotting
    • Generate and plot image histogram
    • Histogram equalization
    • Histogram matching (prescriptive)
    • function adapthisteq
  • Spatial filtering
    • Linear Spatial Filtering
    • Nonlinear Spatial Filtering
  • Standard Spatial Filters for Image Processing Toolbox
    • Linear Spatial Filter
    • nonlinear spatial filter

1. Grayscale transformation function

g(x, y) = T[f(x, y)]

The value of g at (x, y) is only determined by the grayscale of f at that point, and T also becomes a function of brightness or grayscale. The two terms are used interchangeably when dealing with monochrome images. When working with color images, luminance is used to represent a color image component in some color space.

Functions imadjust and stretchlim
  • Grayscale image for grayscale transformation

    g = imadjust(f, [low_in high_in], [low_out high_out], gamma)


Values ​​between [low_in high_in] map to [low_out high_out]. If gamma
>> g1 = imadjust(f, [0 1], [1 0]);
>> imshow(g1);
>> g = imcomplement(f);
>> imshow(g);

image f (original image)
write picture description here
image g, g1
image

imadjust(f, [0 1], [1 0])
imcomplement(f)
Both functions can represent the negative of the image

>> g3 = imadjust(f, [], [], 0.5);
>> imshow(g3);
You can also directly change the gamma value
>> g3 = imadjust(f, stretchlim(f), []);
>> imshow(g3);

For g3 images, the stretchlim(f) function implements contrast stretching, which increases the contrast by default.
write picture description here

Logarithmic and Contrast Stretch Transformations
Contrast stretching is to expand a narrow range of input gray levels to a wide range of output gray levels. In my own understanding is to make the contrast effect more obvious, forming a high-contrast image. - a function that performs a logarithmic transformation

gs = im2uint8(mat2gray(g));

The way a function is implemented on a floating-point image in MATLAB is by means of the formula *g = 1 ./ (1 + (m./f) .^ E)*
>> g = im2uint8(mat2gray(z));
>> gs = im2uint8(mat2gray(log(1 + double(z))));
>> imshow(gs);
>> figure, imshow(g);

write picture description here
image

Specify an arbitrary grayscale transformation
To implement grayscale mapping you can use the function

g = interp1(z, T, f)

T is a column vector, z is a column vector with the same length as T, use the following method to achieve

z = linspace(0, 1, numel(T));

==Using floating point numbers in the range [0 1] to represent input and output images greatly simplifies the program==
Practical M-function
  • Detect the number of arguments input to the M function
    n = nargin
  • The number of output arguments of the detection function
    n = nargout
  • Check if the number of arguments passed is correct
    msg = nargchk(low, high, number)
  • Variable number of input and output variables
    Generally , when writing functions, we often encounter uncertain parameters, we can use varargin and varargout.
function [m, n] = testhv3(varargin)
function [varargout] = testhv4(m, n)
%可以有一个固定的输入参数,后面跟随可变数量的输入参数
function [m, n] = testhv3(x, varargin)
  • Another M function for grayscale transformation
    1.intrans.m
    2.gammaTransform.m
    3.stretchTransform.m
    4.spcfiedTransform.m
    5.logTransform.m The
    above five functions are used in combination
>> g = intrans(f, 'stretch', mean2(im2double(f)), 0.9);
>> figure, imshow(g);

A function that implements grayscale transformation
- grayscale calibration

function g = gscale(f, varargin)
if length(varargin) == 0
    method = 'full8';
else
    method = varargin{1};
end

if strcmp(class(f), 'double') && (max(f(:))>1 || min(f(:))<0)
   f = mat2gray(f);
end

switch method
    case 'full8'
        g = im2uint8(mat2gray(double(f)));
    case 'full16'
        g = im2uint16(mat2gray(double(f)));
    case 'minmax'
       low = varargin{2};high = varargin{3};
       if low>1 | low<0 | high>1 | high<0
             error('Parameters low and high must be in the range [0,1]')
       end
       if strcmp(class(f), 'double')
            low_in = min(f(:));
            high_in = max(f(:));
       elseif strcmp(class(f), 'uint8')
            low_in = double(min(f(:)))./255;
            high_in = double(max(f(:)))./255;
       elseif strcmp(class(f), 'uint16')
            low_in = double(min(f(:)))./65535;
            high_in = double(max(f(:)))./65535;
       end

       g = imadjust(f,[low_in high_in],[low high]);
otherwise
       error('Unknown method')
end

call the following statement

g = gscale(f, method, low, high)

Valid values ​​for method are 'full8' (default), 'full16' and 'minmax'.

2. Histogram processing and function drawing

Generate and plot image histogram
h(rk) = nk

rk is the k-th grayscale in the interval [0, G]

nk is the number of pixels where rk appears

p(rk) = h(rk) / n = nk / n

p(rk) is the probability estimate of the occurrence of gray level rk

  • The imhist method of the histogram

There is a core function for processing histograms

h = imhist(f, b);

b is the number of "bins" used to form the histogram (if b is not included in this parameter, its default value is 256).

>> imhist(f);

image

==A container is just a small part of the grayscale range, b is to divide the 256 levels into b parts==

Method to normalize histogram:
p = imhist(f, b) / numel(f)
- bar method

>> h = imhist(ff, 25);
>> horz = linspace(0, 155, 25);
>> bar(horz, h)
>> axis([0 255 0 60000])
>> set(gca, 'xtick', 0:50:255)
>> set(gca, 'ytick', 0:20000:60000)
>> figure, imshow(h);
>> figure, imshow(ff);

image

==linspace(x1,x2,N)==

Function: linspace is an average calculation instruction in Matlab, which is used to generate a linear vector of N points between x1 and x2. Among them, x1, x2, and N are the starting value, ending value, and the number of elements, respectively. If the default is N, the default number of points is 100.

==axis([horzmin horzmax vertmin vertmax])==

Function: Set the range of the horizontal and vertical axes

set(gca, ‘xtick’, 0:50:255)

It means that the x-axis is set to increase from 0 to 50 each time until it increases to 255, and the same is true for the y-axis.

  • stem method
>> h = imhist(f, 25);
>> horz = linspace(0, 255, 25);
>> stem(horz, h, 'fill')

image
- plot method

>> hc = imhist(ff);
>> plot(hc)
>> axis([0 255 0 15000])
>> set(gca, 'xtick', [0:50:255])
>> set(gca, 'ytick', [0:2000:15000])

image

The gca in ==set is used to return the handle of the current axes (coordinate map) object, that is, a coordinate image is returned. ==

ylim ('auto')
xlim ('auto')

Automatically set the range of x, y that meets the conditions. It can also be set manually, same as below.

ylim([ymin ymax])
xlim([xmin xmax])

  • Drawing functions that handle function handles

    fplot(fhandle, limits, ‘LineSpec’)


limits is a vector specifying the range of values ​​for the x-axis of the function (xmin, xmax), and 'LineSpec' is the symbol to draw the image.
>> fandle = @sin

fandle =

  function_handle with value:

    @sin

>> fplot(fandlw, [0 6], ':')

image

A graph of a sine function is drawn between 0 and 6.

Other functions can also be used to beautify the image

>> fandle.LineStyle = ':';
>> fandle.Color = 'r';
>> fandle.Marker = 'x';
>> fandle.MarkerEdgeColor = 'b';

image

Histogram equalization
  • Histogram equalization function

    g = histeq(f, nlev)


nlev is the number of gray levels set for the output image histogram
, the default nlev = 64 in the function, and the general gray level will be divided into 256 levels.
>> f = Fig0208;
>> imshow(f);
>> figure, imhist(f);
>> ylim('auto')

Here is the original image and its histogram
image

image

After histogram equalization

>> g = histeq(f, 256);
>> figure, imshow(g);
>> figure, imhist(g);
>> ylim('auto')

image

image

The histogram accumulation and summation lists the entire process of grayscale changes
(the cumsum function represents the accumulation and summation, such as

A = 1:5;

B = cumsum(A)

B = 1 3 6 10 15)

>> hnorm = imhist(f) ./ numel(f);
>> cdf = cumsum(hnorm);
>> x = linspace(0, 1, 256);
>> plot(x, cdf)
>> axis([0 1 0 1])
>> set(gca, 'xtick', 0:.2:1)
>> set(gca, 'ytick', 0:.2:1)
>> xlabel('Input intensity values', 'fontsize', 9)
>> ylabel('Output intensity values', 'fontsize', 9)

image

==You can use Insert in the window to modify the inserted graphics==

Histogram matching (prescriptive)
  • Histogram matching function
    g = histeq(f, hspec)
>> imshow(f);
>> figure, imhist(f);
>> g = histeq(f, 256);
>> figure, imshow(g);
>> figure, imhist(g);

image

image

The grayscale is shifted to the higher end in the given toolbox function, but still gives a low contrast and washed out image. It can be seen from the original image that the gray levels are too concentrated at and around 0. The cumulative transformation function obtained with the histogram is very steep, so the pixels that are too concentrated at the low end are mapped to the high end of the gray level.

Using histogram matching can remedy this phenomenon.
- Histogram matching enhancements

>> g = histeq(f, p);
>> imshow(g);
>> figure, plot(p);
>> ylim('auto')
>> figure, imhist(g);

image

image

image

function adapthisteq

This function performs so-called contrast-limited adaptive histogram equalization, which uses histogram matching method to process small regions (patches) in the image one by one, and then combines adjacent patches, thereby == eliminating artificial introduction bounds == .

g = adapthisteq (f, param1, val1, param2, val2…)

param/val is the content of the table

image

>> g1 = adapthisteq(f);
>> g2 = adapthisteq(f, 'NumTiles', [25 25]);
>> g3 = adapthisteq(f, 'NumTiles', [25 25], 'ClipLimit', 0.05);

As can be seen from the figure, the local enhancement method is better than the global enhancement, but the additional cost is increased complexity of the function.

image

3. Spatial filtering

Linear Spatial Filtering
Linear operation understanding: For a 3 x 3 filter, the coefficients on all filters are multiplied by the pixels of the corresponding points, and all the results are summed to obtain the response of the 3 x 3 center in the image. There are some points that do not overlap when the image and the template are processed. It is necessary to fill f with enough and necessary 0 to ensure that there are corresponding points in the whole process of the template w passing through f. == Odd-sized templates are more intuitive, with a clear center point. ==
  • Correlation and Convolution

Related: Handle image arrays as understood above.

Convolution: The image array is processed in the same way after the template is rotated by 180 degrees.
- full and same

'full': Fill the image and perform related calculations.
'same': produces a correlation of the same size as f. This calculation is also padded with zeros, but starts at the position where the origin of f is aligned with the center of the template.
- Implements linear spatial filtering

g = imfilter(f, w, filtering_mode, boundary_options, size_option)

w is the filter template, filtering_mode is 'corr' for related completion filtering, and 'conv' is specified for convolution; boundary_options handles the boundary filling problem, and the boundary size is determined by the filter size; size_option is either 'same' or 'full'.

>> f = im2double(f);
>> subplot(231), imshow(f), title('f');
>> w = ones(31);
>> gd = imfilter(f, w);
>> subplot(232), imshow(gd, []), title('gd');
>> gr = imfilter(f, w, 'replicate');
>> subplot(233), imshow(gr, []), title('gr');
>> gs = imfilter(f, w, 'symmetric');
>> subplot(234), imshow(gs, []), title('gs');
>> gc = imfilter(f, w, 'circular');
>> subplot(235), imshow(gc, []), title('gc');
>> f8 = im2uint8(f);
>> g8r = imfilter(f, w, 'replicate');
>> subplot(236), imshow(g8r, []), title('g8r');

image

nonlinear filtering

Linear filtering is based on computing the sum of products, while non-linear filtering is based on non-linear operations involving pixels in the neighborhood surrounded by the filter.
- Nonlinear filter processing function

g = colifilt(f, [m n], ‘sliding’, fun)

'Sliding' indicates that the mxn area slides pixel by pixel in the input image f during processing, and fun is the function handle.

>> f = Fig0216;
>> subplot(121), imshow(f);
>> gmean = @(A)prod(A, 1) .^ 1/size(A, 1);
>> g = colfilt(f, [5 5], 'sliding', gmean);
>> subplot(122), inshow(g);

image

  • border fill

    fp = padarry(f, [r c], method, direction)


image

4. Standard Spatial Filters of Image Processing Toolbox

Linear Spatial Filtering
  • Linear Spatial Filter Implementation Function

    w = fspecial(‘type’, parameters)


'type' defines the type of filter, parameters further specify the filter.
image
  • Implementing a Laplace filter
>> f = Fig0217;
>> w = [0 1 0; 1 -4 1; 0 1 0];
>> g1 = imfilter(f, w, 'replicate');
>> f2 = im2double(f);
>> g2 = imfilter(f2, w, 'replicate');
>> g = f2 - g2;
>> subplot(141), imshow(f)
>> subplot(142), imshow(g1, [ ])
>> subplot(143), imshow(g2, [ ])
>> subplot(144), imshow(g)

image

Subtracting the Laplacian image from the original image is the enhanced image.

  • Comparison of hand-specified filters and enhancement techniques
>> f = Fig0217;
>> w4 = fspecial('laplacian', 0);
>> w8 = [1 1 1; 1 -8 1; 1 1 1];
>> f = im2double(f);
>> g4 = f - imfilter(f, w4, 'replicate');
>> g8 = f - imfilter(f, w8, 'replicate');
>> subplot(131), imshow(f);
>> subplot(132), imshow(g4);
>> subplot(133), imshow(g8);

image

The image sharpness gradually increases, using a Laplacian filter with a center factor of -8 to be the sharpest of the three images.

nonlinear spatial filter

The response of these nonlinear spatial filters is based on ordering the pixels contained in the image neighborhood, and then having the value determined by the ordering replace the center pixel in the neighborhood.

g = ordfilt2(f, order, domain)

Replace each element of f with order elements, where domain is a matrix of 0s and 1s of size mxn.


  • median filter

g = ordfilt2(f, (m * n + 1) / 2, ones(m, n))
g = medfilt2(f, [m n], padopt)

[mn] defines a neighborhood of size mxn, padopt specifies three possible boundary padding options: 'zeros' (the default), 'symmetric' indicates that f extends symmetrically along the boundary according to mirror reflection, and 'indexed' indicates that if If f is a double class, it is filled with 1, otherwise it is filled with 0.

>> f = Fig0219;
>> fn = imnoise(f, 'salt & pepper', 0.2);
>> subplot(141), imshow(f);
>> subplot(142), imshow(fn);
>> gm = medfilt2(fn);
>> subplot(143), imshow(gm);
>> gms = medfilt2(fn, 'symmetric');
>> subplot(144), imshow(gms);

image

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325686371&siteId=291194637