Formation of a bitonal image by the threshold Thr - matlab

I have a task - The formation of a bitonal image on the threshold of Thr. If the pixel brightness value exceeds the threshold, then it is replaced by the maximum (in our case by 255), otherwise by the minimum, i.e. by 0. But at the output, the image behaves strangely from the side, tell me how to fix it?
The result obtained
function decomp_new(array, thr, filename, FH, IH, RGBQUAD0, RGBQUAD1)
FID = fopen(filename, 'w');
fwrite(FID, FH.bfTYPE, 'uchar');
fwrite(FID, FH.bfSIZE, 'ulong');
fwrite(FID, FH.bfR1, 'uint8');
fwrite(FID, FH.bfR2, 'uint8');
fwrite(FID, FH.bfOFFBITS, 'ulong');
fwrite(FID, IH.biSIZE, 'ulong');
fwrite(FID, IH.biWIDTH, 'ulong');
fwrite(FID, IH.biHEIGHT, 'ulong');
fwrite(FID, IH.biPLANES, 'uint16');
fwrite(FID, 1, 'uint16'); %IH.biBITCOUNT
fwrite(FID, IH.biCOMPRESSION, 'ulong');
fwrite(FID, IH.biSIZEIMAGE, 'ulong');
fwrite(FID, IH.biXPELSPERMETER, 'ulong');
fwrite(FID, IH.biYPELSPERMETER, 'ulong');
fwrite(FID, IH.biCLRUSED, 'ulong'); %IH.biCLRUSED
fwrite(FID, IH.biCLRIMPORTANT, 'ulong');
fwrite(FID, IH.tmp, 'uint8');
fwrite(FID, RGBQUAD0.RED, 'uint8');
fwrite(FID, RGBQUAD0.GREEN, 'uint8');
fwrite(FID, RGBQUAD0.BLUE, 'uint8');
fwrite(FID, RGBQUAD0.RESERVED, 'uint8');
fwrite(FID, RGBQUAD1.RED, 'uint8');
fwrite(FID, RGBQUAD1.GREEN, 'uint8');
fwrite(FID, RGBQUAD1.BLUE, 'uint8');
fwrite(FID, RGBQUAD1.RESERVED, 'uint8');
for i = 1 : 3 : length(array)
B = array(i);
G = array(i+1);
R = array(i+2);
Y = 0.299 * R + 0.587 * G + 0.114 * B;
if (Y > thr)
fwrite(FID, 1, 'ubit1','ieee-be');
end
if (Y <= thr)
fwrite(FID, 0, "ubit1','ieee-be');
end
end
fclose(FID);
end

Related

binary file write/read operation in Matlab

I am trying to write some 2D coordinates into a binary file. However, what I read from the file that had been writen is quite different from the original data. Details are given here.
For example, I have 45 (X,Y) points. Both X and Y are integral number less than 600. The simulation requires store each of them with two bytes (8 bits) and 2 upper bits of each byte is reserved (for X, the reserved bits are filled by .mrk which is 1 or 2; for Y, simply use 0 instead). In this case, 14 bits binary number is able to represent the maximum, 16383. I write the data in several ways:
in_tmp is structure consisted of points number (.nm), points reserved mark (.mrk) and points coordinates (.coor)
for i=1:in_tmp.nm
x1 = dec2bin(in_tmp.coor(i,1));
y1 = dec2bin(in_tmp.coor(i,2));
t1 = in_tm.mrk(i);
if(t1==1)
t2 = '01';
t2b = 1;
elseif(t1==2)
t2 = '10';
t2b = 2;
end
lenx = 16-length(x1);
leny = 16-length(y1);
x1hl = strcat(t2, '00000000000000'); % High and low
y1hl = '0000000000000000';
x1a = strcat(x1hl(1:lenx), num2str(x1));
y1a = strcat(y1hl(1:leny), num2str(y1));
y1a(1:2) = '00';
% x1b = in_tmp.coor(i,1);
% y1b = in_tmp.coor(i,2);
% fwrite(fp1, t2b, 'ubit2');
% fwrite(fp1, x1b, 'ubit14');
%
% fwrite(fp1, 0, 'ubit2');
% fwrite(fp1, y1b, 'ubit14');
fwrite(fp1, bin2dec(x1a), 'uint16');
fwrite(fp1, bin2dec(y1a), 'uint16');
% fwrite(fp1, bin2dec(x1a(1:8)), 'uint8');
% fwrite(fp1, bin2dec(x1a(9:end)), 'uint8');
% fwrite(fp1, bin2dec(y1a(1:8)), 'uint8');
% fwrite(fp1, bin2dec(y1a(9:end)), 'uint8');
% x1c = in_tmp.coor(i,1);
% y1c = in_tmp.coor(i,2);
%
% x1hex = dec2hex(x1c);
% y1hex = dec2hex(y1c);
% if(length(x1hex)>2)
% x1h = x1hex(1:end-2);
% x1l = x1hex(end-1:end);
% else
% x1h = dec2hex(0);
% x1l = x1hex;
% end
%
% tx1h = dec2bin(hex2dec(x1h));
% l1 = length(tx1h);
% bin0 = dec2bin(128); % '10000000'
% if(t1==1)
% bin0(end-l1+1:end) = tx1h;
% bin0(1)=0;
% bin0(2)=1;
%
% elseif(t1==2)
% bin0(end-l1+1:end) = tx1h;
% end
% x1h = bin2dec(tx1h);
%
% if(length(y1hex)>2)
% y1h = y1hex(1:end-2);
% y1l = y1hex(end-1:end);
% else
% y1h = dec2hex(0);
% y1l = y1hex;
% end
% fwrite(fp1, x1h, 'uint8');
% fwrite(fp1, hex2dec(x1l), 'uint8');
% fwrite(fp1, hex2dec(y1h), 'uint8');
% fwrite(fp1, hex2dec(y1l), 'uint8');
end
The way I read it
for i=1:mt.nm % nm points.
mred(i,6) = fread(fp1, 1, 'uint8'); % Raw X coordinates.
mred(i,7) = fread(fp1, 1, 'uint8'); % upper 2 bits are reserved info.
tmpx = [dec2bin(mred(i,6)), dec2bin(mred(i,7))];
if(length(tmpx)==16)
mred(i,4) = bin2dec(tmpx(1:2)); % Real Mark.
mred(i,1) = bin2dec(tmpx(3:end)); % Real X.
elseif(length(tmpx)==15)
mred(i,4) = bin2dec(tmpx(1)); % Real Type.
mred(i,1) = bin2dec(tmpx(2:end)); % Real X.
else
mred(i,4) = bin2dec(tmpx(1:2)); % Type unknown.
mred(i,1) = bin2dec(tmpx(3:end)); % Real X.
end
mred(i,8) = fread(fp1, 1, 'uint8'); % Y coordinates.
mred(i,9) = fread(fp1, 1, 'uint8'); % upper 2 bits are reserved.
tmpy = [dec2bin(mred(i,8)), dec2bin(mred(i,9))];
if(length(tmpy)==16)
mred(i,10) = bin2dec(tmpy(1:2)); % Real reserved.
mred(i,2) = bin2dec(tmpy(3:end)); % Real Y.
elseif(length(tmpy)==15)
mred(i,10) = bin2dec(tmpy(1)); % Real reserved.
mred(i,2) = bin2dec(tmpy(2:end)); % Real Y.
else
mred(i,10) = -1; % Reserved unknown.
mred(i,2) = bin2dec(tmpy); % Real Y.
end
end
The read() function works well for a given software which is implemented via C++. The software generates coordinates series in such a format. Then, I prepare a read() to get the information in the binary file generated by C++ software. Then, I want to implement the write() with Matlab in that format, but the read() fails to obtain what I had written to the binary file. Anybody help? Thanks.
The problem is probably (at least in part) an endian issue.
On intel architecture (little endian), reading two bytes as uint8 followed by appending the binary representations is not going to give you the same result in general as reading two bytes as uint16.
The following script illustrates how swapping the order of the two uint8's will do the trick.
I changed some variable names and made things more concise for readability.
% declare an input int and the header (in binary string rep)
v = 68;
t2 = '01';
% write to file
x1 = dec2bin(v);
lenx = 16-length(x1);
x1hl = strcat(t2, '00000000000000'); % High and low
x1a = strcat(x1hl(1:lenx), num2str(x1));
% x1a = 0100000001000100
fp1=fopen('temp','w+');
fwrite(fp1, bin2dec(x1a), 'uint16');
% read the file
frewind(fp1);
vtest = fread(fp1, 1, 'uint16'); % upper 2 bits are reserved info.
dec2bin(vtest)
% ans = 100000001000100
% now read *two* bytes as two uint8
frewind(fp1);
byte1 = fread(fp1, 1, 'uint8'); % Raw X coordinates.
byte2 = fread(fp1, 1, 'uint8'); % upper 2 bits are reserved info.
tmpx = [dec2bin(byte2) dec2bin(byte1)]; % <-- swap the order
% tmpx = 10000001000100
Alternately just read the whole 2 bytes as uint16 and work from there.

bmpinfoheader for writing BMP images

I'm trying to write a MATLAB code for writing file to BMP file.
I know I can use imwrite() function. But my task is to avoid it.
I need info about how to write bmpinfoheader? So far I only know that it is 14-bits array.
8-bit BMP
%---- BitMapfileHeader
fwrite(fid, hex2dec('42'), 'uchar'); % 'B' in ASCII code
fwrite(fid, hex2dec('4D'), 'uchar'); % 'M' in ASCII code
fwrite(fid, 54 + sz + 256 * 4, 'ulong'); % file size
fwrite(fid, 0, 'ushort'); % always 0
fwrite(fid, 0, 'ushort'); % always 0
fwrite(fid, 54 + 256 * 4, 'ulong'); % offset
%---- BitMapInfoHeader
fwrite(fid, 40, 'ulong'); % BitMapInfoHeader size
fwrite(fid, width, 'long'); % image width
fwrite(fid, height, 'long'); % image height (negative; positive=upside-down)
fwrite(fid, 1, 'ushort'); % always 1
fwrite(fid, 8, 'ushort'); % color bit
fwrite(fid, 0, 'ulong'); % compression
fwrite(fid, sz, 'ulong'); % image size
fwrite(fid, dpm, 'long'); % horizontal resolution (dpm)
fwrite(fid, dpm, 'long'); % vertical resolution (dpm)
fwrite(fid, 256, 'ulong'); % # of color index
fwrite(fid, 0, 'ulong'); % # of important color index
24-bit BMP
%---- BitMapfileHeader
fwrite(fid, hex2dec('42'), 'uchar'); % 'B' in ASCII code
fwrite(fid, hex2dec('4D'), 'uchar'); % 'M' in ASCII code
fwrite(fid, 54 + sz, 'ulong'); % file size
fwrite(fid, 0, 'ushort'); % always 0
fwrite(fid, 0, 'ushort'); % always 0
fwrite(fid, 54, 'ulong'); % offset
%---- BitMapInfoHeader
fwrite(fid, 40, 'ulong'); % BitMapInfoHeader size
fwrite(fid, width, 'long'); % image width
fwrite(fid, height, 'long'); % image height (negative; positive=upside-down)
fwrite(fid, 1, 'ushort'); % always 1
fwrite(fid, 24, 'ushort'); % color bit
fwrite(fid, 0, 'ulong'); % compression
fwrite(fid, sz, 'ulong'); % image size
fwrite(fid, dpm, 'long'); % horizontal resolution (dpm)
fwrite(fid, dpm, 'long'); % vertical resolution (dpm)
fwrite(fid, 0, 'ulong'); % # of color index
fwrite(fid, 0, 'ulong'); % # of important color index
Source - http://www.h6.dion.ne.jp/~fff/old/technique/matlab/matlab_V.html
Or look at the structure here
http://msdn.microsoft.com/en-us/library/windows/desktop/dd183376(v=vs.85).aspx http://www.herdsoft.com/ti/davincie/davp3xo2.htm

Dlmwrite doesn't give any output to .xls

I have a Matlab file that reads a text file getting values for r, c and Beta. Using those 3 columns I want to combine this with a file in Matlab with airfoil coordinates which I eventually split up in slices (I want around 30 pieces) of X and Y coordinates.
The problem I'm facing is that the dlmwrite doesn't give any output files. The file did work before, but now I don't see any xls file appearing. I have looked at the dlmwrite specifically, but I can't find my mistake.
n is the number of slices I want to create, which is equal to the number of lines in the text file which contains r, c and Beta. The Z = ones(81,1) is the number of airfoil coordinates (X and Y together counts as 1)
clear all
close all
clc
%Create and output propeller geometry text files for solidworks
Propeller_Geometry = 'lllllaatsten.txt';
Airfoil_Geometry = 'as5048.txt'; %airfoil x_c, z_c
[r, c, beta] = textread(Propeller_Geometry) % (m, m, deg)
[x_c, z_c] = textread(Airfoil_Geometry); %(-, -)
c = c * 1000; % Chord Length (mm)
r = r * 1000; % Radius Length (mm)
beta = beta * pi / 180; % Angle from rotational velocity vector to lower blade edge (rad)
n = 50; % Number of slices
hold on
plot(x_c, z_c, '-b')
axis([0 1 -0.5 0.5])
xlabel('Unit Chord ( x/c)', 'fontsize', 14)
ylabel('Unit Height (z/c)', 'fontsize', 14)
title('TA22 Airfoil Geometry', 'fontsize', 14)
%Create dimensional slices
for i=1:n+1
x = x_c * c(i); % Dimensional Chord (mm)
y = z_c * c(i); % Dimensional Height (mm)
X = x * cos(-beta(i)) - y * sin(-beta(i)); % Rotated x-coordinate
Y = y * cos(-beta(i)) + x * sin(-beta(i)); % Rotated y-coordinate
Z = ones(81,1) * r(i);
P = horzcat(-X, Y, Z);
%dlmwrite(['Slice_' int2str(i)'.xls'], P, 'delimiter', '\t', 'precision', 8)
%dlmwrite(['stuk_' int2str(i) '.txt'], P, 'delimiter', '\t', 'precision', 8)
dlmwrite (['stuk_' int2str(i) '.xls'], P, '-append', 'delimiter', '\t', 'newline', 'pc')
plot3(Z, -X, Y); %cm
axis([0 50 -30 0 -7 1])
xlabel('Radius (mm)', 'fontsize', 18)
ylabel('Chord (mm)', 'fontsize', 18)
zlabel('Height (cm)', 'fontsize', 18)
title('Propeller geometry', 'fontsize', 18)
grid
end

input must be empty or a format string

Hi I keep getting an error with this:
%% generate sample data
K = 3;
numObservarations = 12000;
dimensions = 20;
data = fopen('M.dat','rt');
C = textscan(data,[numObservarations dimensions]);
??? Error using ==> textscan
Second input must be empty or a format string.
I tryed this method:
%% format data
%# read the list of features
fid = fopen('kddcup.names','rt');
C = textscan(fid, '%s %s', 'Delimiter',':', 'HeaderLines',1);
fclose(fid);
%# determine type of features
C{2} = regexprep(C{2}, '.$',''); %# remove "." at the end
attribNom = [ismember(C{2},'symbolic');true]; %# nominal features
%# build format string used to read/parse the actual data
frmt = cell(1,numel(C{1}));
frmt( ismember(C{2},'continuous') ) = {'%f'}; %# numeric features: read as number
frmt( ismember(C{2},'symbolic') ) = {'%s'}; %# nominal features: read as string
frmt = [frmt{:}];
frmt = [frmt '%s']; %# add the class attribute
%# read dataset
fid = fopen('kddcup.data_10_percent_corrected','rt');
C = textscan(fid, frmt, 'Delimiter',',');
fclose(fid);
%# convert nominal attributes to numeric
ind = find(attribNom);
G = cell(numel(ind),1);
for i=1:numel(ind)
[C{ind(i)},G{i}] = grp2idx( C{ind(i)} );
end
%# all numeric dataset
M = cell2mat(C);
data = M;
%% generate sample data
K = 3;
numObservarations = 12000;
dimensions = 20;
data = textscan([numObservarations dimensions]);
%% cluster
opts = statset('MaxIter', 500, 'Display', 'iter');
[clustIDX, clusters, interClustSum, Dist] = kmeans(data, K, 'options',opts, ...
'distance','sqEuclidean', 'EmptyAction','singleton', 'replicates',3);
%% plot data+clusters
figure, hold on
scatter3(data(:,1),data(:,2),data(:,3), 50, clustIDX, 'filled')
scatter3(clusters(:,1),clusters(:,2),clusters(:,3), 200, (1:K)', 'filled')
hold off, xlabel('x'), ylabel('y'), zlabel('z')
%% plot clusters quality
figure
[silh,h] = silhouette(data, clustIDX);
avrgScore = mean(silh);
%% Assign data to clusters
% calculate distance (squared) of all instances to each cluster centroid
D = zeros(numObservarations, K); % init distances
for k=1:K
%d = sum((x-y).^2).^0.5
D(:,k) = sum( ((data - repmat(clusters(k,:),numObservarations,1)).^2), 2);
end
% find for all instances the cluster closet to it
[minDists, clusterIndices] = min(D, [], 2);
% compare it with what you expect it to be
sum(clusterIndices == clustIDX)
but get the error:
??? Error using ==> textscan
Invalid file identifier. Use fopen to
generate a valid file identifier.
Error in ==> kmeans at 37
data = textscan([numObservarations
dimensions]);
Your call of textscan is not compliant with the syntax required. The following signatures are valid:
C = textscan(fid, 'format')
C = textscan(fid, 'format', N)
C = textscan(fid, 'format', 'param', value)
C = textscan(fid, 'format', N, 'param', value)
C = textscan(str, ...)
[C, position] = textscan(...)

MATLAB: filter noisy EKG signal

What is the best filter to use to remove noise from an ECG signal with matlab?
If you have access to the Signal Processing Toolbox, then check out the Savitzky-Golay filter, namely the function sgolay. There's an accompanying demo, just run sgolaydemo.
The following is an example to show the various ways you can apply filtering and de-noising to a signal. Note some of these functions requires certain toolboxes to be present:
% load ecg: simulate noisy ECG
Fs=500;
x = repmat(ecg(Fs), 1, 8);
x = x + randn(1,length(x)).*0.18;
% plot noisy signal
figure
subplot(911), plot(x), set(gca, 'YLim', [-1 1], 'xtick',[])
title('noisy')
% sgolay filter
frame = 15;
degree = 0;
y = sgolayfilt(x, degree, frame);
subplot(912), plot(y), set(gca, 'YLim', [-1 1], 'xtick',[])
title('sgolayfilt')
% smooth
window = 30;
%y = smooth(x, window, 'moving');
%y = smooth(x, window/length(x), 'sgolay', 2);
y = smooth(x, window/length(x), 'rloess');
subplot(913), plot(y), set(gca, 'YLim', [-1 1], 'xtick',[])
title('smooth')
% moving average filter
window = 15;
h = ones(window,1)/window;
y = filter(h, 1, x);
subplot(914), plot(y), set(gca, 'YLim', [-1 1], 'xtick',[])
title('moving average')
% moving weighted window
window = 7;
h = gausswin(2*window+1)./window;
y = zeros(size(x));
for i=1:length(x)
for j=-window:window;
if j>-i && j<(length(x)-i+1)
%y(i) = y(i) + x(i+j) * (1-(j/window)^2)/window;
y(i) = y(i) + x(i+j) * h(j+window+1);
end
end
end
subplot(915), plot( y ), set(gca, 'YLim', [-1 1], 'xtick',[])
title('weighted window')
% gaussian
window = 7;
h = normpdf( -window:window, 0, fix((2*window+1)/6) );
y = filter(h, 1, x);
subplot(916), plot( y ), set(gca, 'YLim', [-1 1], 'xtick',[])
title('gaussian')
% median filter
window = 15;
y = medfilt1(x, window);
subplot(917), plot(y), set(gca, 'YLim', [-1 1], 'xtick',[])
title('median')
% filter
order = 15;
h = fir1(order, 0.1, rectwin(order+1));
y = filter(h, 1, x);
subplot(918), plot( y ), set(gca, 'YLim', [-1 1], 'xtick',[])
title('fir1')
% lowpass Butterworth filter
fNorm = 25 / (Fs/2); % normalized cutoff frequency
[b,a] = butter(10, fNorm, 'low'); % 10th order filter
y = filtfilt(b, a, x);
subplot(919), plot(y), set(gca, 'YLim', [-1 1])
title('butterworth')
Two filter design tools/demos that you may want to check out:
FDATool in the Signal Processing Toolbox (if you have access to it).
Analog Filter Design Toolbox from James Squire on the MathWorks File Exchange. There appear to be simulations for fitering EKG data included in the toolbox.
These should give you a chance to try out different filters and filter parameters to see how they perform with EKG/ECG data.