Color halftone with MATLAB - image

How to color halftone using MATLAB code ?
I first used jarvis black and white half tone then modified it color halftone.
My approach :-
function outImg = jarvisColorHalftone(inImg)
[N,M,P] = size(inImg);
outImg = logical(zeros([N,M,P]));
for p = 1:P
outImg(:,:,p) = jarvisHalftone(inImg(:,:,p));
end
outImg;
The function above is not working.
// jarvisHalftone function for grayscale to black and white image
function outImg = jarvisHalftone(inImg)
inImg = double(inImg);
[M,N] = size(inImg);
T = 127.5;
y = inImg;
error = 0;
y= [127.5*ones(M,2) y 127.5*ones(M,2) ; 127.5*ones(2,N+4)];
z = y;
for rows = 1:M
for cols = 3:N+2
z(rows,cols) =255*(y(rows,cols)>=T);
error = -z(rows,cols) + y(rows,cols);
y(rows,cols+2) = 5/48 * error + y(rows,cols+2);
y(rows,cols+1) = 7/48 * error + y(rows,cols+1);
y(rows+1,cols+2) = 3/48 * error + y(rows+1,cols+2);
y(rows+1,cols+1) = 5/48 * error + y(rows+1,cols+1);
y(rows+1,cols+0) = 7/48 * error + y(rows+1,cols+0);
y(rows+1,cols-1) = 5/48 * error + y(rows+1,cols-1);
y(rows+1,cols-2) = 3/48 * error + y(rows+1,cols-2);
y(rows+2,cols+2) = 1/48 * error + y(rows+2,cols+2);
y(rows+2,cols+1) = 3/48 * error + y(rows+2,cols+1);
y(rows+2,cols+0) = 5/48 * error + y(rows+2,cols+0);
y(rows+2,cols-1) = 3/48 * error + y(rows+2,cols-1);
y(rows+2,cols-2) = 1/48 * error + y(rows+2,cols-2);
end
end
outImg = z(1:M,3:N+2);
outImg = im2bw(uint8(outImg));

Related

Experimenting inverting pictures with Octave

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')

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_);

How to make a vertical wave with using canvas?

I changed the script by adding text instead of an image.
I want to wave was vertically downwards. I know that a little editing but I tried different options and it did not work.
http://jsfiddle.net/7ynn4/3/
var options = {
period:100,
squeeze:0,
wavelength:40,
amplitude:30,
shading:300,
fps:30
}
var ca = document.getElementById('canvas');
var ctx = ca.getContext('2d');
ctx.canvas.width = 400;
ctx.canvas.height = 150;
ctx.font = 'bold 45pt Arial';
ctx.textAlign = 'center';
ctx.fillStyle = 'blue';
ctx.fillText('Hello World', 170, 60);
w = canvas.width,
h = canvas.height,
od = ctx.getImageData( 0, 0, w, h ).data;
setInterval(function() {
var id = ctx.getImageData( 0, 0, w, h ),
d = id.data,
now = ( new Date() )/options.period,
y,
x,
lastO,
shade,
sq = ( y - h/2 ) * options.squeeze,
px,
pct,
o,
y2,
opx;
for ( y = 0; y < h; y += 1 ) {
lastO = 0;
shade = 0;
sq = ( y - h/2 ) * options.squeeze;
for ( x = 0; x < w; x += 1 ) {
px = ( y * w + x ) * 4;
pct = x/w;
o = Math.sin( x/options.wavelength - now ) * options.amplitude * pct;
y2 = y + ( o + sq * pct ) << 0;
opx = ( y2 * w + x ) * 4;
shade = (o-lastO) * options.shading;
d[px ] = od[opx ]+shade;
d[px+1] = od[opx+1]+shade;
d[px+2] = od[opx+2]+shade;
d[px+3] = od[opx+3];
lastO = o;
}
}
ctx.putImageData( id, 0, 0 );
},
1000/options.fps
);
You just flip the values around so that x is affected instead of y -
... vars cut, but replace y2 with x2 ...
/// reversed from here
for (x = 0; x < w; x += 1) {
lastO = 0;
shade = 0;
sq = (x - w * 0.5) * options.squeeze;
for (y = 0; y < h; y += 1) {
px = (y * w + x) * 4;
pct = y / h;
o = Math.sin(y/options.wavelength-now) * options.amplitude * pct;
/// the important one: you might need to compensate here (-5)
x2 = x - 5 + (o + sq * pct) | 0;
opx = (x2 + y * w) * 4;
shade = (o - lastO) * options.shading;
d[px] = od[opx] + shade;
d[px + 1] = od[opx + 1] + shade;
d[px + 2] = od[opx + 2] + shade;
d[px + 3] = od[opx + 3];
lastO = o;
}
}
ctx.putImageData(id, 0, 0);
MODIFIED FIDDLE HERE

How to accelerate matlab code?

I'm using matlab to implement a multilayer neural network. In the code I represent
the value of each node AS netValue{k}
the weight between layer k and k + 1 AS weight{k}
etc.
Since these data is three-dimensional, I have to use cell to hold a 2-D matrix to enable matrix multiply.
So it becomes really really slow to train the model, which I expect to have resulted from the usage of cell.
Can anyone tell me how to accelerate this code? Thanks
clc;
close all;
clear all;
input = [-2 : 0.4 : 2;-2:0.4:2];
ican = 4;
depth = 4; % total layer - 1, by convension
[featureNum , sampleNum] = size(input);
levelNum(1) = featureNum;
levelNum(2) = 5;
levelNum(3) = 5;
levelNum(4) = 5;
levelNum(5) = 2;
weight = cell(0);
for k = 1 : depth
weight{k} = rand(levelNum(k+1), levelNum(k)) - 2 * rand(levelNum(k+1) , levelNum(k));
threshold{k} = rand(levelNum(k+1) , 1) - 2 * rand(levelNum(k+1) , 1);
end
runCount = 0;
sumMSE = 1; % init MSE
minError = 1e-5;
afa = 0.1; % step of "gradient ascendence"
% training loop
while(runCount < 100000 & sumMSE > minError)
sumMSE = 0; % sum of MSE
for i = 1 : sampleNum % sample loop
netValue{1} = input(:,i);
for k = 2 : depth
netValue{k} = weight{k-1} * netValue{k-1} + threshold{k-1}; %calculate each layer
netValue{k} = 1 ./ (1 + exp(-netValue{k})); %apply logistic function
end
netValue{depth+1} = weight{depth} * netValue{depth} + threshold{depth}; %output layer
e = 1 + sin((pi / 4) * ican * netValue{1}) - netValue{depth + 1}; %calc error
assistS{depth} = diag(ones(size(netValue{depth+1})));
s{depth} = -2 * assistS{depth} * e;
for k = depth - 1 : -1 : 1
assistS{k} = diag((1-netValue{k+1}).*netValue{k+1});
s{k} = assistS{k} * weight{k+1}' * s{k+1};
end
for k = 1 : depth
weight{k} = weight{k} - afa * s{k} * netValue{k}';
threshold{k} = threshold{k} - afa * s{k};
end
sumMSE = sumMSE + e' * e;
end
sumMSE = sqrt(sumMSE) / sampleNum;
runCount = runCount + 1;
end
x = [-2 : 0.1 : 2;-2:0.1:2];
y = zeros(size(x));
z = 1 + sin((pi / 4) * ican .* x);
% test
for i = 1 : length(x)
netValue{1} = x(:,i);
for k = 2 : depth
netValue{k} = weight{k-1} * netValue{k-1} + threshold{k-1};
netValue{k} = 1 ./ ( 1 + exp(-netValue{k}));
end
y(:, i) = weight{depth} * netValue{depth} + threshold{depth};
end
plot(x(1,:) , y(1,:) , 'r');
hold on;
plot(x(1,:) , z(1,:) , 'g');
hold off;
Have you used the profiler to find out what functions are actually slowing down your code? It shows what lines take the most time to execute.

Find the distance from camera to vanishing point in matlab

I have this program that finds the vanishing point for a given set of images. Is there a way to find the distance from the camera and the vanishing point?
Also once the vanishing point is found out, I manually need to find the X and Y coordinates using the tool provided in matlab. How can i code a snippet that writes all the X and Y coordinates into a text or excel file?
Also is there a better and simpler way to find the vanishing point in matlab?
Matlab Calling Function to find Vanishing Point:
clear all; close all;
dname = 'Height';
files = dir(dname);
files(1) = [];
files(1) = [];
for i=1:size(files, 1)
original = imread(fullfile(dname, files(i).name));
original = imresize(original,0.35);
im = im2double(rgb2gray(original));
[row, col] = findVanishingPoint(im);
imshow(original);hold;plot(col,row,'rx');
saveas(gcf,strcat('Height_Result',num2str(i)),'jpg');
close
end
The findVanishingPoint function:
function [row, col] = findVanishingPoint(im)
DEBUG = 0;
IM = fft2(im);
ROWS = size(IM,1); COLS = size(IM,2);
PERIOD = 2^floor(log2(COLS)-5)+2;
SIZE = floor(10*PERIOD/pi);
SIGMA = SIZE/9;
NORIENT = 72;
E = 8;
[C, S] = createGaborBank(SIZE, PERIOD, SIGMA, NORIENT, ROWS, COLS, E);
D = ones(ROWS, COLS);
AMAX = ifftshift(real(ifft2(C{1}.*IM)).^2+real(ifft2(S{1}.*IM))).^2;
for n=2:NORIENT
A = ifftshift(real(ifft2(C{n}.*IM)).^2+real(ifft2(S{n}.*IM))).^2;
D(find(A > AMAX)) = n;
AMAX = max(A, AMAX);
if (DEBUG==1)
colormap('hot');subplot(131);imagesc(real(A));subplot(132);imagesc(real(AMAX));colorbar;
subplot(133);imagesc(D);
pause
end
end
if (DEBUG==2)
figure('DoubleBuffer','on');
end
T = mean(AMAX(:))-3*std(AMAX(:));
VOTE = zeros(ROWS, COLS);
for row=round(1+SIZE/2):round(ROWS-SIZE/2)
for col=round(1+SIZE/2):round(COLS-SIZE/2)
if (AMAX(row,col) > T)
indices = lineBresenham(ROWS, COLS, col, row, D(row, col)*pi/NORIENT-pi/2);
VOTE(indices) = VOTE(indices)+AMAX(row,col);
end
end
if (DEBUG==2)
colormap('hot');imagesc(VOTE);pause;
end
end
if (DEBUG==2)
close
end
M=1;
[b index] = sort(-VOTE(:));
col = floor((index(1:M)-1) / ROWS)+1;
row = mod(index(1:M)-1, ROWS)+1;
col = round(mean(col));
row = round(mean(row));
The creatGaborBank function:
function [C, S] = createGaborBank(SIZE, PERIOD, SIGMA, NORIENT, ROWS, COLS, E)
if (length(NORIENT)==1)
orientations=[1:NORIENT];
else
orientations = NORIENT;
NORIENT = max(orientations);
end
for n=orientations
[C{n}, S{n}] = gabormask(SIZE, SIGMA, PERIOD, n*pi/NORIENT);
C{n} = fft2(padWithZeros(C{n}, ROWS, COLS));
S{n} = fft2(padWithZeros(S{n}, ROWS, COLS));
end
The gabormask function:
function [cmask, smask] = gabormask(Size, sigma, period, orient, E)
if nargin < 5; E = 8; end;
if nargin < 4; orient = 0; end;
if nargin < 3; period = []; end;
if nargin < 2; sigma = []; end;
if nargin < 1; Size = []; end;
if isempty(period) & isempty(sigma); sigma = 5; end;
if isempty(period); period = sigma*2*sqrt(2); end;
if isempty(sigma); sigma = period/(2*sqrt(2)); end;
if isempty(Size); Size = 2*round(2.575*sigma) + 1; end;
if length(Size) == 1
sx = Size-1; sy = sx;
elseif all(size(Size) == [1 2])
sy = Size(1)-1; sx = Size(2)-1;
else
error('Size must be scalar or 1-by-2 vector');
end;
hy = sy/2; hx = sx/2;
[x, y] = meshgrid(-hx:sx-hx, -hy:sy-hy);
omega = 2*pi/period;
cs = omega * cos(orient);
sn = omega * sin(orient);
k = -1/(E*sigma*sigma);
g = exp(k * (E*x.*x + y.*y));
xp = x * cs + y * sn;
cx = cos(xp);
cmask = g .* cx;
sx = sin(xp);
smask = g .* sx;
cmask = cmask - mean(cmask(:));
cmask = cmask/sum(abs(cmask(:)));
smask = smask - mean(smask(:));
smask = smask/sum(abs(smask(:)));
The padWithZeros function:
function out = padWithZeros(in, ROWS, COLS)
out = padarray(in,[floor((ROWS-size(in,1))/2) floor((COLS-size(in,2))/2)],0,'both');
if size(out,1) == ROWS-1
out = padarray(out,[1 0],0,'pre');
end
if size(out,2) == COLS-1
out = padarray(out,[0 1],0,'pre');
end
The findHorizonEdge function:
function row = findHorizon(im)
DEBUG = 2;
ROWS = size(im,1); COLS = size(im,2);
e = edge(im,'sobel', [], 'horizontal');
dd = sum(e, 2);
N=3;
row = 1;
M = 0;
for i=1+N:length(dd)-N
m = sum(dd(i-N:i+N));
if (m > M)
M = m;
row = i;
end
end
imshow(e);pause
The findHorizon function:
function row = findHorizon(im)
DEBUG = 2;
IM = fft2(im);
ROWS = size(IM,1); COLS = size(IM,2);
PERIOD = 2^floor(log2(COLS)-5)+2;
SIZE = floor(10*PERIOD/pi);
SIGMA = SIZE/9;
NORIENT = 72;
E = 16;
orientations = [NORIENT/2-10:NORIENT/2+10];
[C, S] = createGaborBank(SIZE, PERIOD, SIGMA, orientations, ROWS, COLS, E);
ASUM = zeros(ROWS, COLS);
for n=orientations
A = ifftshift(real(ifft2(C{n}.*IM)).^2+real(ifft2(S{n}.*IM))).^2;
ASUM = ASUM + A;
if (DEBUG==1)
colormap('hot');subplot(131);imagesc(real(A));subplot(132);imagesc(real(AMAX));colorbar;
pause
end
end
ASUM(1:round(1+SIZE/2), :)=0; ASUM(end-round(SIZE/2):end, :)=0;
ASUM(:,end-round(SIZE/2):end)=0; ASUM(:, 1:1+round(SIZE/2))=0;
dd = sum(ASUM, 2);
[temp, row] = sort(-dd);
row = round(mean(row(1:10)));
if (DEBUG == 2)
imagesc(ASUM);hold on;line([1:COLS],repmat(row,COLS));
pause
end
The lineImage function:
function v = lineimage(x0, y0, angle, s)
if (abs(tan(angle)) > 1e015)
a(1,:) = repmat(x0,s(1),1)';
a(2,:) = [1:s(1)];
elseif (abs(tan(angle)) < 1e-015)
a(2,:) = repmat(y0,s(2),1)';
a(1,:) = [1:s(2)];
else
k = tan(angle);
hiX = round((1-(s(1)-y0+1)+k*x0)/k);
loX = round((s(1)-(s(1)-y0+1)+k*x0)/k);
temp = max(loX, hiX);
loX = max(min(loX, hiX), 1);
hiX = min(s(2),temp);
a(1,:) = [loX:hiX];
a(2,:) = max(1, floor(s(1)-(k*a(1,:)+(s(1)-y0+1)-k*x0)));
end
v = (a(1,:)-1).*s(1)+a(2,:);
The lineVector function:
function [abscissa, ordinate] = linevector(x0, y0, angle, s)
if (rad2deg(angle) == 90)
abscissa = repmat(x0,s(1),1);
ordinate = [1:s(1)];
else
k = tan(angle);
hiX = round((1-(s(1)-y0+1)+k*x0)/k);
loX = round((s(1)-(s(1)-y0+1)+k*x0)/k);
temp = max(loX, hiX);
loX = max(min(loX, hiX), 1);
hiX = min(s(2),temp);
abscissa = [loX:hiX];
ordinate = k*abscissa+((s(1)-y0+1)-k*x0);
end
The lineBresenham function:
function [i] = lineBresenham(H,W,Sx,Sy,angle)
k = tan(angle);
if (angle == pi || angle == 0)
Ex = W;
Ey = Sy;
Sx = 1;
elseif (angle == pi/2)
Ey = 1;
i = (Sx-1)*H+[Ey:Sy];
return;
elseif k>0 & k < (Sy-1)/(W-Sx)
Ex = W;
Ey = round(Sy-tan(angle)*(Ex-Sx));
elseif k < 0 & abs(k) < (Sy-1)/(Sx-1)
Ex = 1;
Ey = round(Sy-tan(angle)*(Ex-Sx));
else
Ey = 1;
Ex = round((Sy-1)/tan(angle)+Sx);
end
Dx = Ex - Sx;
Dy = Ey - Sy;
iCoords=1;
if(abs(Dy) <= abs(Dx))
if(Ex >= Sx)
D = 2*Dy + Dx;
IncH = 2*Dy;
IncD = 2*(Dy + Dx);
X = Sx;
Y = Sy;
i(iCoords) = (Sx-1)*H+Sy;
iCoords = iCoords + 1;
while(X < Ex)
if(D >= 0)
D = D + IncH;
X = X + 1;
else
D = D + IncD;
X = X + 1;
Y = Y - 1;
end
i(iCoords) = (X-1)*H+Y;
iCoords = iCoords + 1;
end
else
D = -2*Dy + Dx;
IncH = -2*Dy;
IncD = 2*(-Dy + Dx);
X = Sx;
Y = Sy;
i(iCoords) = (Sx-1)*H+Sy;
iCoords = iCoords + 1;
while(X > Ex)
if(D <= 0)
D = D + IncH;
X = X - 1;
else
D = D + IncD;
X = X - 1;
Y = Y - 1;
end
i(iCoords) = (X-1)*H+Y;
iCoords = iCoords + 1;
end
end
else
Tmp = Ex;
Ex = Ey;
Ey = Tmp;
Tmp = Sx;
Sx = Sy;
Sy = Tmp;
Dx = Ex - Sx;
Dy = Ey - Sy;
if(Ex >= Sx)
D = 2*Dy + Dx;
IncH = 2*Dy;
IncD = 2*(Dy + Dx);
X = Sx;
Y = Sy;
i(iCoords) = (Sy-1)*H+Sx;
iCoords = iCoords + 1;
while(X < Ex)
if(D >= 0)
D = D + IncH;
X = X + 1;
else
D = D + IncD;
X = X + 1;
Y = Y - 1;
end
i(iCoords) = (Y-1)*H+X;
iCoords = iCoords + 1;
end
else
D = -2*Dy + Dx;
IncH = -2*Dy;
IncD = 2*(-Dy + Dx);
X = Sx;
Y = Sy;
i(iCoords) = (Sy-1)*H+Sx;
iCoords = iCoords + 1;
while(X > Ex)
if(D <= 0)
D = D + IncH;
X = X - 1;
else
D = D + IncD;
X = X - 1;
Y = Y - 1;
end
i(iCoords) = (Y-1)*H+X;
iCoords = iCoords + 1;
end
end
end
The vanishing point is at infinity hence the distance to the camera is of no use.
Use xlswrite or dlmwrite to write into excel or text file respectively.

Resources