Unable to get contrast of image as described by its formula - matlab

I was trying to get the contrast of an image using a formula but the contrast value is not exceeding 255. As well as whenever I tried to make some operation on my image matrix the element values also not exceeding 255. I tried converting the image matrix to double but the element values changed and are not equal to original pixel values.
clc;
clear all;
close all;
h = imread('C:\Users\LAXMIDHAR\Desktop\My proj files\abc.jpg');
g = rgb2gray(h);
% f = im2double(g);
[M,N] = size(g);
%
% for i=1:M
% for j=1:N
% f(i,j) = f(i,j).*((i-j).^2);
% end
% end
%
% s = sum(sum(f));
s = 0;
for i = 1:M
for j=1:N
s = s+(g(i,j).*((i-j).^2));
end
end
% s is the contrast of image
s is expected to be large but its not exceeding 255. This is the contrast formula:

Related

Directional artifacts in MATLAB randn arrays?

I'm generating 3d fractal noise in MATLAB using a variety of methods. It's working relatively well, but I'm having an issue where I see vertical striping artifacts in my noise. This happens regardless of what data type or resolution I use.
Edit: I figured it out. The solution is posted as an answer below. Thanks everyone for your thoughts and guidance!
expo = 2^6;
dims = [expo,expo,expo];
beta = -4.5;
render = randnd(beta, dims); % Create volumetric fractal
render = render - min(render); % Set floor to zero
render = render ./ max(render); % Set ceiling to one
%render = imbinarize(render); % BW Threshold option
render = render .* 255; % For greyscale
slicer = 1; % Turn on image slicer/saver
i = 0; % Page counter
format = '.png';
imagename = '___testDump/slice';
imshow(render(:,:,1),[0 255]); %Single test image
if slicer == 1
for c = 1:length(render)
i = i+1;
pagenumber = num2str(i);
filename = [imagename, pagenumber, format];
imwrite(uint8(render(:,:,i)),filename)
end
end
function X = randnd(beta,varargin)
seed = 999;
rng(seed); % Set seed
%% X = randnd(beta,varargin)
% Based on similar functions by Jon Yearsley and Hristo Zhivomirov
% Written by Marcin Konowalczyk
% Timmel Group # Oxford University
%% Parse the input
narginchk(0,Inf); nargoutchk(0,1);
if nargin < 2 || isempty(beta); beta = 0; end % Default to white noise
assert(isnumeric(beta) && isequal(size(beta),[1 1]),'''beta'' must be a number');
assert(-6 <= beta && beta <= 6,'''beta'' out of range'); % Put on reasonable bounds
%% Generate N-dimensional white noise with 'randn'
X = randn(varargin{:});
if isempty(X); return; end; % Usually happens when size vector contains zeros
% Squeeze prevents an error if X has more than one leading singleton dimension
% This is a slight deviation from the pure functionality of 'randn'
X = squeeze(X);
% Return if white noise is requested
if beta == 0; return; end;
%% Generate corresponding N-dimensional matrix of multipliers
N = size(X);
% Create matrix of multipliers (M) of X in the frequency domain
M = [];
for j = 1:length(N)
n = N(j);
if (rem(n,2)~=0) % if n is odd
% Nyquist frequency bin does not show up in odd-numbered fft
k = ifftshift(-(n-1)/2:(n-1)/2);
else
k = ifftshift(-n/2:n/2-1);
end
% Spectral multipliers
m = (k.^2)';
if isempty(M);
M = m;
else
% Create the permutation vector
M_perm = circshift(1:length(size(M))+1,[0 1]);
% Permute a singleton dimension to the beginning of M
M = permute(M,M_perm);
% Add m along the first dimension of M
M = bsxfun(#plus,M,m);
end
end
% Reverse M to match X (since new dimensions were being added form the left)
M = permute(M,length(size(M)):-1:1);
assert(isequal(size(M),size(X)),'Bad programming error'); % This should never occur
% Shape the amplitude multipliers by beta/4 which corresponds to shaping the power by beta
M = M.^(beta/4);
% Set the DC component to zero
M(1,1) = 0;
%% Multiply X by M in frequency domain
Xstd = std(X(:));
Xmean = mean(X(:));
X = real(ifftn(fftn(X).*M));
% Force zero mean unity standard deviation
X = X - mean(X(:));
X = X./std(X(:));
% Restore the standard deviation and mean from before the spectral shaping.
% This ensures the random sample from randn is truly random. After all, if
% the mean was always exactly zero it would not be all that random.
X = X + Xmean;
X = X.*Xstd;
end
Here is my solution:
My "min/max" code (lines 6 and 7) was bad. I wanted to divide all values in the matrix by the single largest value in the matrix so that all values would be between 0 and 1. Because I used max() improperly, I was stepping through the max value of each column and using that as my divisor; thus the vertical stripes.
In the end this is what my code looks like. X is the 3 dimensional matrix:
minVal = min(X,[],'all'); % Get the lowest value in the entire matrix
X = X - minVal; % Set min value to zero
maxVal = max(X,[],'all'); % Get the highest value in the entire matrix
X = X ./ maxVal; % Set max value to one

Creating a heatmap of the logistic map for different values of lambda in matlab

So I am trying to create a heatmap of the logistic map for lambda =2.5 till lambda 4, showing that some outcomes are more common than others as part of my thesis. However so far I did not came far. I plotted the logistic map, however the heatmap part is a bit of a hassle and I can't find how to do it. So, how do I create a heatmap using the coding that I have?
% Logistics Map
% Classic chaos example. Plots semi-stable values of
% x(n+1) = r*x(n)*(1-x(n)) as r increases to 4.
%
clear
scale = 1000; % determines the level of rounding
maxpoints = 200; % determines maximum values to plot
N = 3000; % number of "r" values to simulate
a = 2.5; % starting value of "r"
b = 4; % final value of "r"... anything higher diverges.
rs = linspace(a,b,N); % vector of "r" values
M = 500; % number of iterations of logistics equation
% Loop through the "r" values
for j = 1:length(rs)
r=rs(j); % get current "r"
x=zeros(M,1); % allocate memory
x(1) = 0.5; % initial condition (can be anything from 0 to 1)
for i = 2:M, % iterate
x(i) = r*x(i-1)*(1-x(i-1));
end
% only save those unique, semi-stable values
out{j} = unique(round(scale*x(end-maxpoints:end)));
end
% Rearrange cell array into a large n-by-2 vector for plotting
data = [];
for k = 1:length(rs)
n = length(out{k});
data = [data; rs(k)*ones(n,1),out{k}];
end
% Plot the data
figure(97);clf
h=plot(data(:,1),data(:,2)/scale,'b.');
set(h,'markersize',0.25)
ylim([0 1])
set(gcf,'color','w')
Thanks a lot in advance!

Ploting a simple binaryThresholding function graph in matlab as shown in image and figure

How can I correct this code, I have been trying to do it from 2 day but unable to do it still. Please help.
function BinaryThresholding(I)
%Reading minimum and maximum intensity values of Image I.
Min = min(I(:));
Max = max(I(:));
%Finding the middle value (thresholding) A.K.A m below.
m = (Min+Max)/2;
%For ploting the thresholding tranformation function we will also
%define X and Y (Ranges) parameters based upon min and max range and the
%process them according to our transformation algoritm as below.
x = (Min/Max):(Max/Max); %input range.
y = x;
% Now we will apply alogithm to threshold the threshold I at
% the middle intensity,thresholdingValue, of its dynamic
% range [minValue maxValue]. G is our processed image.
[Rows, Columns, Channels] = size(I);
%First we will check if the image is gray-scale and conver it if not.
if(Channels==3)
I = rgb2gray(I);
end
%Processing Image.
for i=1:1:Rows
for j=1:1:Columns
if( I(i,j)< m)
G(i,j) = 0;
else
G(i,j) = 1;
end
end
end
% Algorithm works great :D --> Testingw with : figure, imshow(G);
%Displaying image on a new figure window.
figure('Name','Image Thresholding','NumberTitle','on'),
subplot(1,3,1); imshow(I); title(['Input Image - Dynamic Range: [',num2str(Min),' ',num2str(Max),']']);
subplot(1,3,2); imshow(G); title(['Output Image - Threshold:' num2str(m)]);
subplot(1,3,3); plot(x,y); title('Plot of Thresholding Transformation Function');
%Let pixel info to be shown on the figure.
impixelinfo;
%Writing the image G as a .png file to the current folder (Drive D:/).
% imwrite(G,'D:/G.png');
endDesired output
Actual output
From the title of outputs I think you want to fix this line
subplot(1,3,3); plot(x,y); title('Plot of Thresholding Transformation Function');
which means only correct these couple of lines
x = (Min/Max):(Max/Max); %input range.
y = x;
that means: x is equally spaced from min to max... and Y is also equally spaced from min to max (as you can see from your actual output). Try something like:
x = (Min/Max):(Max/Max); %input range.
y = zeros(length(x));
for i=1:length(x)
if (x > m)
y(i) = 1;
end
end

connected component analysis in MATLAB

I want to apply connected component analysis on a grey scale image with considering pixels whose grey level is more than a threshold. then, I want to remove those connected components whose length is less than a threshold. please help me? I wrote following code in MATLAB, is it efficient?
thank you in advance.
%im = input image;
% alpha1 = 0.0001;
% alpha2 = 0.0001;
% [row col] = size(im);
%
%
% thr1 = mean(mean(im))-alpha1*std(std(im));
% BW = zeros(size(im));
%
% for rr = 1:row
% for cc = 1:col
% if im(rr,cc)>thr2
% BW(rr,cc) = 1;
% else
% BW(rr,cc) = 0;
% end
% end
% end
%
% CC = bwconncomp(BW);
% area_in_pixels = cellfun(#length,CC.PixelIdxList);
% thr2 = mean(area_in_pixels)-alpha2*std(area_in_pixels);
% idx = find(area_in_pixels <= thr3);
% for kk = 1:length(idx)
% aaa = idx(kk);
% BW(CC.PixelIdxList{aaa})=0;
% end
You can try regionprops instead to extract all objects in your image. With the code below you get the positions of all objects smaller than a threshold which you can manipulate or do what you need to do afterwards...
Comparably you can go through the different objects and extract the grey level and if it is below a threshold manipulate them.
% Threshold for the size in pixels that you want
threshold = 100;
% read your image
rawimage = imread('yourimage.jpg');
% create a 2D field by summing
im = sum(rawimage,3);
% label all objects that have 8 neighbours
IMAGE_labeled = bwlabel(im,8);
% get the properties of all elements
shapedata=regionprops (IMAGE_labeled,'all');
% get those elements that are smaller in size (area) than the threshold
index = find(cell2mat({shapedata(:).Area})<=threshold);
% make a contourplot of im
figure
contourf(im)
hold on
% creation of colormap with the size of all identified objects below the thres
mycolormap = jet(size(index,2));
% loop over all small objects, extraction of their position in the original file, plotting circles with different colors at the position of each small object
imap = 1;
mean_of_red = zeros(length(index),1);
for i = index
plot (shapedata(i).PixelList(:,1),shapedata(i).PixelList(:,2),'o','MarkerFaceColor',mycolormap(imap,:))
mean_of_red(i) = mean(mean(im(shapedata(i).PixelList(:,1),shapedata(i).PixelList(:,1),1)));
imap=imap+1;
end

Image corruption in matlab parfor loop

I have some code for an adaptive median filter (see below) which works perfectly until I attempt to run it as a parallel loop, in which case there are values missing or corrupted and the image I get at the end is incorrect (see http://i.stack.imgur.com/Rt6dV.jpg).
Matlab doesn't throw up any errors but appears to be either dropping random data, or overwriting them. The only thing I could find which would even vaguely match this problem was information on custom type definitions and set functions, but all of my input images are uint8 so I don't have any custom set functions or type definitions. (http://fluffynukeit.com/problems-with-matlab-parfor-data-disappearing/)
The error occurs specifically between lines 63 and 86, when I attempt to change
for Index = 1:length(ss)
to
parfor Index = 1:length(ss)
and I can't for the life of me figure out why.
I usually call the function with an image, I, in uint8 format (although any format should work), w_size is an odd number relating to the size of the window for filtering, and M can be set from 0 to 2, where lower numbers reduce the amount of pixels considered when median filtering by increasing the weight of the standard deviation of the current block. So a typical function call would be thus:
I = imread('image.tif');
J = Par_AMF(I, 5, 1);
figure;
imshow(J)
I should finish by saying that typically the size of images I'm using make the parallel processing a huge time saver, usually about half the time of the non-parallel execution, so although there isn't much point for smaller images the ones I'm using would really benefit from it.
function [FIm] = Par_AMF(Im, w_size, M)
% PAR_AMF Adaptive median filter
% Performs a local adaptive median filtering operation
% Inputs: Im - Image to be filtered
% w_size - Window size for filter
% M - Sigma weighting, range from 0 to 2
%
% Output: FIm - Filtered image
tic;
sz_oldim = size(Im);
w_option = floor(w_size/2);
% ----------------------------------------------------------------------- %
% Padding edges of image matrix
Pad_im = padarray(Im,[w_option, w_option],0,'both');
% ----------------------------------------------------------------------- %
% Stage 1
% Calculate the local Mean and Standard Deviation for finding Speckle
% Pixels
% ----------------------------------------------------------------------- %
sz = size(Pad_im);
start_index = w_option+1;
end_index1=(sz(1)-w_option);
end_index2=(sz(2)-w_option);
LB = zeros(sz_oldim);
UB = LB;
first_loop1 = start_index:end_index1;
first_loop2 = start_index:end_index2;
ss = cell(numel(LB), 1);
Index = 1;
for c = first_loop2
for r = first_loop1
ss{Index} = Pad_im(r-w_option:r+w_option,c-w_option:c+w_option);
Index = Index+1;
end
end
% This parfor functions as expected:
parfor Index = 1:length(ss)
ss1=ss{Index}(:);
if any(ss1 > 0)
local_mn = mean(ss1);
local_sig = std(double([ss1;local_mn]));
LB(Index) = local_mn - (M*local_sig);
UB(Index) = local_mn + (M*local_sig);
end
end
% ----------------------------------------------------------------------- %
% UB is the Upper Bound Limit; LB is the Lower Bound Limit
% ----------------------------------------------------------------------- %
% ----------------------------------------------------------------------- %
% Using UB and LB mark pixels as speckle or valid pixels and update only if
% central pixel of window is speckle pixels with median value calculated
% again with only speckle pixels with the window
% ----------------------------------------------------------------------- %
TempOut = Im;
% When this for loop is changed to a parfor (which should definitely work)
% the output is corrupted horribly:
% parfor Index = 1:length(ss)
for Index = 1:length(ss)
ss1 = ss{Index}(:);
ss2 = ss1;
if any(ss1>0)
zz = 0;
for z = 1:length(ss1)
if (ss1(z) < LB(Index) || ss1(z) > UB(Index))
ss1(z) = 0;
ss2(z) = 0;
else
ss1(z)=1;
zz= zz+1;
end
end
if zz > 0
new_ss1 = ss2(ss2~=0);
if(ss1(ceil(length(ss1)/2)) == 0)
md = median(new_ss1);
TempOut(Index) = md;
end
end
end
end
looptime = toc;
disp(['Total processing time ', num2str(looptime./60), ' minutes'])
FIm = TempOut;
end
EDIT: In Matlab version R2015a