Experimenting inverting pictures with Octave - image

First time using Octave to experiment inverting an image. My filename is LinearAlgebraLab1.m and after I run the file with Octave I get error "error: no such file, '/home/LinearAlgebraLab1.m'"
However, before this, I was getting an error that my .jpg file couldn't be found. What should I change to have Octave run my script correctly without any errors?
%% import image
C = imread('MonaLisa2.jpg');
%% set slopes and intercepts for color transformation
redSlope = 1;
redIntercept = -80;
greenSlope = -.75;
greenIntercept = 150;
blueSlope = -.50;
blueIntercept = 200;
%%redSlope = 1;
%%redIntercept = -80;
%%greenSlope = -.75;
%%greenIntercept = 150;
%%blueSlope = -.50;
%%blueIntercept = 200; redSlope = 1;
%% store RGB channels from image separately
R = C(:,:,1);
G = C(:,:,2);
B = C(:,:,3);
C2 = C;
S=size(C);
m=S(1,1);
n=S(1,2);
%h=S(1,3);
%% change red channel
M = R;
%%M2 = redSlope*cast(M,'double') + redIntercept*ones(786,579);
M2 = redSlope*cast(M,'double') + redIntercept*ones(m,n);
C2(:,:,1) = M2;
%% change green channel
M = G;
M2 = greenSlope*cast(M,'double') + greenIntercept*ones(m,n);
C2(:,:,2) = M2;
%% change blue channel
M = B;
M2 = blueSlope*cast(M,'double') + blueIntercept*ones(m,n);
C2(:,:,3) = M2;
%% visualize new image
image(C2)
axis equal tight off
set(gca,'position',[0 0 1 1],'units','normalized')

Related

How to properly process images with mixed noise types

The picture with noise is like this.
Noised picture: Image3.bmp
I was doing image processing in MatLab with some built-in and self-implemented filters.
I have already tried a combination of bilateral, median and gaussian. bilateral and gaussian code are at the end of this post.
img3 = double(imread('Image3.bmp')); % this is the noised image
lena = double(imread('lena_gray.jpg')); % this is the original one
img3_com = bilateral(img3, 3, 2, 80);
img3_com = medfilt2(img3_com, [3 3], 'symmetric');
img3_com = gaussian(img3_com, 3, 0.5);
img3_com = bilateral(double(img3_com), 6, 100, 13);
SNR3_com = snr(img3_com,img3_com - lena); % 17.1107
However, the result is not promising with SNR of only 17.11.
Filtered image: img3_com
The original picture is like this.
Clean original image: lena_gray.jpg
Could you please give me any possible ideas about how to process it? Like what noise generators generated the noised image and what filtering methods or image processing method I can use to deal with it. Appreciate!!!
My bilateral function bilateral.m
function img_new = bilateral(img_gray, window, sigmaS, sigmaI)
imgSize = size(img_gray);
img_new = zeros(imgSize);
for i = 1:imgSize(1)
for j = 1:imgSize(2)
sum = 0;
simiSum = 0;
for a = -window:window
for b = -window:window
x = i + a;
y = j + b;
p = img_gray(i,j);
q = 0;
if x < 1 || y < 1 || x > imgSize(1) || y > imgSize(2)
% q=0;
continue;
else
q = img_gray(x,y);
end
gaussianFilter = exp( - double((a)^2 + (b)^2)/ (2 * sigmaS^2 ) - (double(p-q)^2)/ (2 * sigmaI^2 ));
% gaussianFilter = gaussian((a^2 + b^2)^(1/2), sigma) * gaussian(abs(p-q), sigma);
sum = sum + gaussianFilter * q;
simiSum = simiSum + gaussianFilter;
end
end
img_new(i,j) = sum/simiSum;
end
end
% disp SNR
lena = double(imread('lena_gray.jpg'));
SNR1_4_ = snr(img_new,img_new - lena);
disp(SNR1_4_);
My gaussian implementation gaussian.m
function img_gau = gaussian(img, hsize, sigma)
h = fspecial('gaussian', hsize, sigma);
img_gau = conv2(img,h,'same');
% disp SNR
lena = double(imread('lena_gray.jpg'));
SNR1_4_ = snr(img_gau,img_gau - lena);
disp(SNR1_4_);

Color image pixel permutation not reversible

I performed color image permutation using 2D sine-map for RGB image. The code uses this map to perform pixel location permutation for each RGB channel in the image. Then, I used the same map with the same initial parameters to inverse the permutation. The problem is the code only perform correct inverse permutation for one channel only the other channels is not recovered. See the attached images of the permuted and the recovered image.
%% Image Encryption Demo - Encryption and Decryption
clear all
close all
clc
%% 1. Load plaintext images
% Image 1
I = imread('D:\1\1.jpg');
Ir = I(:,:,1);
Ig = I(:,:,2);
Ib = I(:,:,3);
K=1;
%% 2. Encryption
%[CI,K] = Logistic2D_ImageCipher(I,'encryption');
[CIb,K] = Logistic2D_ImageCipher(Ib,'encryption');
clearvars -except CIb Ir Ig Ib K I;
[CIr,K] = Logistic2D_ImageCipher(Ir,'encryption');
clearvars -except CIb CIr Ir Ig Ib K I;
[CIg,K] = Logistic2D_ImageCipher(Ig,'encryption');
clearvars -except CIb CIr CIg Ir Ig Ib K I;
CI = cat(3,CIr,CIg,CIb);
%% 3. Decryption
%DI = Logistic2D_ImageCipher(CI,'decryption',K);
DIb = Logistic2D_ImageCipher(CIb,'decryption',K);
clearvars -except CIb CIr CIg Ir Ig Ib K I DIb CI;
DIg = Logistic2D_ImageCipher(CIg,'decryption',K);
clearvars -except CIb CIr CIg Ir Ig Ib K I DIb DIg CI;
DIr = Logistic2D_ImageCipher(CIr,'decryption',K);
clearvars -except CIb CIr CIg Ir Ig Ib K I DIb DIg DIr CI;
DI = cat(3,DIr,DIg,DIb);
%% 4. Analaysis
% Histogram
%title('aaa');
figure,subplot(221),imshow(I,[]),subplot(222),imshow(CI,[])
subplot(223),imhist(I),subplot(224),imhist(CI)
title('aaa2');
figure,subplot(221),imshow(DI,[])
function varargout = Logistic2D_ImageCipher(P,para,K)
%% 1. Initialization
% 1.1. Genereate Random Key if K is not given
if ~exist('K','var') && strcmp(para,'encryption')
K = round(rand(1,256));
varOutN = 2;
elseif ~exist('K','var') && strcmp(para,'decryption')
error('Cannot Complete Decryption without Encryption Key')
else
varOutN = 1;
end
% 1.2. Translate K to map formats
transFrac = #(K,st,ed) sum(K(st:ed).*2.^(-(1:(ed-st+1))));
x0 = transFrac(K,1,52);
y0 = transFrac(K,53,104);
a=0.8;
b =0.3;
r = transFrac(K,105,156)*.08+1.11;
T = transFrac(K,157,208);
turb = blkproc(K(209:256),[1,8],#(x) bi2de(x));
MN = numel(P);
Logistic2D = #(x,y,a) [sin(pi*a*(y+3)*x*(1-x)), sin(pi*a*(x+3)*y*(1-y))];
format long eng
%% 2. Estimate cipher rounds
if max(P(:))>1
F = 256;
S = 4;
else
F = 2;
S = 32;
end
P = double(P);
iter = 1;
%iter = ceil(log2(numel(P))/log2(S));
%% 3. Image Cipher
C = double(P);
switch para
case 'encryption'
for i = 1:iter
tx0 = mod(log(turb(mod(i-1,6)+1)+i)*x0+T,1);
ty0 = mod(log(turb(mod(i-1,6)+1)+i)*y0+T,1);
xy = zeros(MN,2);
for n = 1:MN
if n == 1
xy(n,:) = (Logistic2D(tx0,ty0,a));
else
xy(n,:) = (Logistic2D(xy(n-1,1),xy(n-1,2),a));
end
end
R = cat(3,reshape(xy(:,1),size(P,1),size(P,2)),reshape(xy(:,2),size(P,1),size(P,2)));
C = LogisticPermutation(C,R,'encryption');
end
case 'decryption'
for i = iter:-1:1
tx0 = mod(log(turb(mod(i-1,6)+1)+i)*x0+T,1);
ty0 = mod(log(turb(mod(i-1,6)+1)+i)*y0+T,1);
xy = zeros(MN,2);
for n = 1:MN
if n == 1
xy(n,:) = (Logistic2D(tx0,ty0,a));
else
xy(n,:) = (Logistic2D(xy(n-1,1),xy(n-1,2),a));
end
end
R = cat(3,reshape(xy(:,1),size(P,1),size(P,2)),reshape(xy(:,2),size(P,1),size(P,2)));
C = LogisticPermutation(C,R,'decryption');
end
end
%% 4. Output
switch F
case 2
C = logical(C);
case 256
C = uint8(C);
end
switch varOutN
case 1
varargout{1} = C;
case 2
varargout{1} = C;
varargout{2} = K;
end
function C = LogisticPermutation(P,R,para)
C0 = zeros(size(P));
C = C0;
switch para
case 'encryption'
% 1. Shuffling within a Column
[v,Epix] = sort(R(:,:,1),1);
for i = 1:size(R,1)
C0(:,i) = P(Epix(:,i),i);
end
% 2. Shuffling within a Row
[v,Epiy] = sort(R(:,:,2),2);
for j = 1:size(R,2)
C(j,:) = C0(j,Epiy(j,:));
end
case 'decryption'
% 1. Shuffling within a Row
[v,Epiy] = sort(R(:,:,2),2);
for j = 1:size(R,2)
C0(j,Epiy(j,:)) = P(j,:);
end
% 2. Shuffling within a Column
[v,Epix] = sort(R(:,:,1),1);
for i = 1:size(R,1)
C(Epix(:,i),i) = C0(:,i);
end
end
It didn't work because you overwrote K in the encryption stage, and it was different for each channel, so the decryption only worked correctly for the last channel that created K. If you're using the MATLAB editor, you should pay attention to the mlint warnings (square at the top right that should be always be green) - you could say that this is what told me the answer to your problem.
Here's a fixed version of the first part of the script:
function q50823167
%% 1. Load plaintext images
% Image 1
I = imread(fullfile(matlabroot, 'examples', 'wavelet', 'mandrill.jpg'));
Ir = I(:,:,1);
Ig = I(:,:,2);
Ib = I(:,:,3);
%% 2. Encryption
%[CI,K] = Logistic2D_ImageCipher(I,'encryption');
[CIb,Kb] = Logistic2D_ImageCipher(Ib,'encryption');
[CIr,Kr] = Logistic2D_ImageCipher(Ir,'encryption');
[CIg,Kg] = Logistic2D_ImageCipher(Ig,'encryption');
CI = cat(3,CIr,CIg,CIb);
%% 3. Decryption
%DI = Logistic2D_ImageCipher(CI,'decryption',K);
DIb = Logistic2D_ImageCipher(CIb,'decryption',Kb);
DIg = Logistic2D_ImageCipher(CIg,'decryption',Kg);
DIr = Logistic2D_ImageCipher(CIr,'decryption',Kr);
DI = cat(3,DIr,DIg,DIb);
%% 4. Analaysis
% Histogram
%title('aaa');
figure,subplot(221),imshow(I,[]),subplot(222),imshow(CI,[])
subplot(223),imhist(I),subplot(224),imhist(CI)
title('aaa2');
figure,subplot(221),imshow(DI,[])
Note that you don't have to clear variables every time.

How to avoid overlapping between title and labels in Matlab's pie chart?

I'm using the next code to plot in a pie chart the percentage of values in a matrix that are greater/smaller than 1. The thing is that when I want to put the title above the graph, it overlaps with the label of one of the groups.
I tried replacing it with text() but it didn't worked, and Documentation on pie say nothing to this. How can I avoid this overlap?
eigen = []; % Modes array
c2 = 170; % Sound speed divided by 2
%% Room dimensions
lx = 5.74;
ly = 8.1;
lz = 4.66;
i = 1; % Index for modes array
for nz = 0:50
for ny = 0:50
for nx = 0:50
aux = c2 * sqrt((nx/lx)^2+(ny/ly)^2+(nz/lz)^2);
if aux < 400 %% If value is into our range of interest
eigen(i) = aux;
i=i+1;
end
end
end
end
eigen = round(sort(eigen'),1);
eigen
% dif = eigen(2:end)-eigen(1:end-1); % Distance between modes
x = 0; %% dif >= 1
y = 0; %% dif <= 1
dif = [];
for i=2:length(eigen)
if eigen(i)-eigen(i-1) >= 1
x = x+1;
else
y = y+1;
end
end
figure
dif = [x,y];
explode = [1 1];
graf = pie(dif,explode);
hText = findobj(graf,'Type','text');
percentValues = get(hText,'String');
txt = {'Smaller than 1 Hz: ';'Greater than 1 Hz: '};
combinedtxt = strcat(txt,percentValues);
oldExtents_cell = get(hText,'Extent');
oldExtents = cell2mat(oldExtents_cell);
hText(1).String = combinedtxt(1);
hText(2).String = combinedtxt(2);
title('Distance between modes')
You can rotate the pie chart so that the figure look better. Further, you can use position to allocate your text as follows,
figure
dif = [x,y];
explode = [1 1];
graf = pie(dif,explode);
hText = findobj(graf,'Type','text');
percentValues = get(hText,'String');
txt = {'Smaller than 1 Hz: ';'Greater than 1 Hz: '};
combinedtxt = strcat(txt,percentValues);
oldExtents_cell = get(hText,'Extent');
oldExtents = cell2mat(oldExtents_cell);
hText(1).String = combinedtxt(1);
hText(2).String = combinedtxt(2);
view([90 90]) % this is to rotate the chart
textPositions_cell = get(hText,{'Position'});
textPositions = cell2mat(textPositions_cell);
textPositions(:,1) = textPositions(:,1) + 0.2; % replace 0.2 with any offset value you want
hText(1).Position = textPositions(1,:);
hText(2).Position = textPositions(2,:);
title('Distance between modes')
You can change only the text position (without rotation) by deleting view command.

Matlab camera oscilloscope

I am at the moment trying to simulate an oscilloscope plugged to the output of a camera in the context of digital film-making.
Here is my code :
clear all;
close all;
clc;
A = imread('06.tif');
[l,c,d] = size(A);
n=256;
B = zeros(n,c);
for i = 1:c
for j = 1:l
t = A(j,i);
B(t+1,i) = B(t+1,i) + 1;
end
end
B = B/0.45;
B = imresize(B,[l c]);
B = (B/255);
C = zeros(n,c);
for i = 1:c
for j = 1:l
t = 0.2126*A(j,i,1)+0.7152*A(j,i,2)+0.0723*A(j,i,3); // here is the supposed issue
C(t+1,i) = C(t+1,i) + 1;
end
end
C = C/0.45;
C = imresize(C,[l c]);
C = (C/255);
figure(1),imshow(B);
figure(2),imshow(C);
The problem is that I am getting breaks in the second image, and unfortunately that's the one I want as an output. My guess is that the issue is located in the linear combination done in the second for but I cannot handle it. I tried with both tif and jpg input, with different data format like uint8 in Matlab but nothing is helping...
Thank you for your attention, I stay available for any question.

I want to correct this code for images, what change need to do..?

Currently i am recognzing a face, means i have to find a face which we have to test is in training database or not..! So, i have to decide yes or no..
Yes means find image, and no means print message that NO IMAGE IN DATABASE. I have a program, Currently this program is finding a correct image correctly, but even when there is no image, even it shows other image which not matches.. Actually it should print NO IMAGE IN DATABASE.
So, How to do..?
Here is a Test and training images data on this link.
http://www.fileconvoy.com/dfl.php?id=g6e59fe8105a6e6389994740914b7b2fc99eb3e445
My Program is in terms of different four .m files, and it is here,we have to run only first code.. and remaining 3 are functions, it is also given here..**
clear all
clc
close all
TrainDatabasePath = uigetdir('D:\Program Files\MATLAB\R2006a\work', 'Select training database path' );
TestDatabasePath = uigetdir('D:\Program Files\MATLAB\R2006a\work', 'Select test database path');
prompt = {'Enter test image name (a number between 1 to 10):'};
dlg_title = 'Input of PCA-Based Face Recognition System';
num_lines= 1;
def = {'1'};
TestImage = inputdlg(prompt,dlg_title,num_lines,def);
TestImage = strcat(TestDatabasePath,'\',char(TestImage),'.jpg');
im = imread(TestImage);
T = CreateDatabase(TrainDatabasePath);
[m, A, Eigenfaces] = EigenfaceCore(T);
OutputName = Recognition(TestImage, m, A, Eigenfaces);
SelectedImage = strcat(TrainDatabasePath,'\',OutputName);
SelectedImage = imread(SelectedImage);
imshow(im)
title('Test Image');
figure,imshow(SelectedImage);
title('Equivalent Image');
str = strcat('Matched image is : ',OutputName);
disp(str)
function T = CreateDatabase(TrainDatabasePath)
TrainFiles = dir(TrainDatabasePath);
Train_Number = 0;
for i = 1:size(TrainFiles,1)
if
not(strcmp(TrainFiles(i).name,'.')|strcmp(TrainFiles(i).name,'..')|strcmp(TrainFiles(i).name,'Thu mbs.db'))
Train_Number = Train_Number + 1; % Number of all images in the training database
end
end
T = [];
for i = 1 : Train_Number
str = int2str(i);
str = strcat('\',str,'.jpg');
str = strcat(TrainDatabasePath,str);
img = imread(str);
img = rgb2gray(img);
[irow icol] = size(img);
temp = reshape(img',irow*icol,1); % Reshaping 2D images into 1D image vectors
T = [T temp]; % 'T' grows after each turn
end
function [m, A, Eigenfaces] = EigenfaceCore(T)
m = mean(T,2); % Computing the average face image m = (1/P)*sum(Tj's) (j = 1 : P)
Train_Number = size(T,2);
A = [];
for i = 1 : Train_Number
temp = double(T(:,i)) - m;
Ai = Ti - m
A = [A temp]; % Merging all centered images
end
L = A'*A; % L is the surrogate of covariance matrix C=A*A'.
[V D] = eig(L); % Diagonal elements of D are the eigenvalues for both L=A'*A and C=A*A'.
L_eig_vec = [];
for i = 1 : size(V,2)
if( D(i,i)>1 )
L_eig_vec = [L_eig_vec V(:,i)];
end
end
Eigenfaces = A * L_eig_vec; % A: centered image vectors
function OutputName = Recognition(TestImage, m, A, Eigenfaces)
ProjectedImages = [];
Train_Number = size(Eigenfaces,2);
for i = 1 : Train_Number
temp = Eigenfaces'*A(:,i); % Projection of centered images into facespace
ProjectedImages = [ProjectedImages temp];
end
InputImage = imread(TestImage);
temp = InputImage(:,:,1);
[irow icol] = size(temp);
InImage = reshape(temp',irow*icol,1);
Difference = double(InImage)-m; % Centered test image
ProjectedTestImage = Eigenfaces'*Difference; % Test image feature vector
Euc_dist = [];
for i = 1 : Train_Number
q = ProjectedImages(:,i);
temp = ( norm( ProjectedTestImage - q ) )^2;
Euc_dist = [Euc_dist temp];
end
[Euc_dist_min , Recognized_index] = min(Euc_dist);
OutputName = strcat(int2str(Recognized_index),'.jpg');
So, how to generate error massege when no image matches..?
At the moment, your application appears to find the most similar image (you appear to be using Euclidean distance as you measure of similarity), and return it. There doesn't seem to be any concept of whether the image "matches" or not.
Define a threshold on similarity, and then determine whether your most similar image meets that threshold. If it does, return it, otherwise display an error message.

Resources