MATLAB: How Can I simulate non uniform background illumination

image processingImage Processing Toolbox

I would like to add non uniform background illumination to some images to test some thresholding algorithms.

Best Answer

If I understand your question correctly you would like to generate images with non-uniform background illumination in order to test thresholding algorithms.
You could try to find a test set of images which already have a non-uniformly illuminated background. For example, rice.png is an image shipped with Image Processing Toolbox with non-uniform illumination. Take a look at that example to see how you could use it:
It's hard to add non-uniform background illumination to images. That would be hard even with Adobe Photoshop. It's easier to create a non-uniform background and then add the foreground. So, why not create images from the ground up using basic functions in MATLAB?
Here's a code snippet that creates a grayscale image with a non-uniform background made of a sinc wave:
% Size of our image: N-by-N
N = 500;
% The xy limits of the sinc function
% we want N points in each direction
x = linspace(-50,50,N);
y = linspace(-50,50,N);
% Transform these xy coordinates into a grid pattern
[X,Y] = meshgrid(x,y);
% The input to the sinc function is the radius from the center
r = sqrt(X.^2 + Y.^2);
% Create the background as the output of sinc
background = sin(r)./r;
% Now we need to scale the matrix so that it is a valid image
mmin = min(background(:));
mmax = max(background(:));
% Subtract the min, divide by the range, multiply by 255 -> values are in [0,255]
background = 255*(background-mmin)/(mmax-mmin);
% Round and cast into uint8 so that it is a valid grayscale image
background = uint8(round(background));
% Now display the result
figure
imshow(background)
% Add objects in the foreground
img = background;
img(100:200,100:200) = 255;
img(150:450,150:350) = 128;
% Display the final image
imshow(img)
You could also do a gradient across the image. For example:
% Create a vector of linearly varying values in x from 100 to 200
x = linspace(100,200,N);
y = 1:N;
% Transform into a grid
[X,Y] = meshgrid(x,y);
% Define the background
background = uint8(round(X));
% Display
imshow(background)
% Add objects in foreground
...
Related Question