Multipage Tiff write in MATLAB doesn't work - matlab

I'm reading in a Tiff using the below function, which works fine, but when I try to use my write function to write that same Tiff back to a different file, it's all 255's. Does anyone know how to fix this? Thanks, Alex.
function Y = tiff_read(name)
% tiff reader that works
info = imfinfo(name);
T = numel(info);
d1 = info(1).Height;
d2 = info(1).Width;
Y = zeros(d1,d2,T);
for t = 1:T
temp = imread(name, t, 'Info',info);
Y(:,:,t) = temp(1:end,1:end);
end
% Tiff writer that doesn't work
function tiff_write(Y,name)
% Y should be 3D, name should end in .tif
T = size(Y,3);
imwrite(Y(:,:,1),name);
for t = 2:T
imwrite(Y(:,:,t),name,'WriteMode','append');
end

Try using this line :
Y = zeros(d1,d2,T,'uint16');
instead of this one:
Y = zeros(d1,d2,T);
Your data are likely in uint16 format and when you export you clip the maximum value to 255 (uint8), which makes pixel with values greater than 255 (a LOT of them if your data is in uint16) appear white.
Otherwise you might want to use this line:
function tiff_write(Y,name)
% Y should be 3D, name should end in .tif
for t = 2:T
imwrite(Y(:,:,t)/255,name,'WriteMode','append');
end

Related

Store integers from a text file into variable arrays

I need to plot some coordinate of x, y in MATLAB using some text file.
and I get a problem with reading it using a for loop.
I can figure it in Python but I need help in converting it in MATLAB.
This is some code in Python
file = open("6.txt", "r")
x = []
y = []
z = []
for i in file.readlines()[::]:
if i[0] == "(":
jam = i.strip('()').split(",")
x.append(float(jam[0]))
y.append(float(jam[1]))
jam = i.strip('()\n').split(",")
z.append(float(jam[2]))
'''
but in Matlab I initially start with this code
fileID = fopen('1.txt', 'r+');
formatSpec = '%s';
for i = fscanf(fileID, '%s')[::]
in Python result is
x = [1.154545 1.265648 ..... 1.56849]
Y = [1.0 1.5655 1.61662 ..... 1.0]
You can try something like:
content=readmatrix('1.txt') %read the entire content as a matrix
x=content(:1) %extract the first column
y=content(:2) %extract the second column
plot(x,y) %plot the data
I cannot test the above code right now, this is why I commented every line that I wrote. But the algorithm remains.

How to add standrad deviation and moving average

What I want to is:
I got folder with 32 txt files and 1 excle file, each file contain some data in two columns: time, level.
I already managed to pull the data from the folder and open each file in Matlab and get the data from it. What I need to do is create plot for each data file.
each of the 32 plots should have:
Change in average over time
Standard deviation
With both of this things I am straggling can't make it work.
also I need to make another plot this time the plot should have the average over each minute from all the 32 files.
here is my code until now:
clc,clear;
myDir = 'my path';
dirInfo = dir([myDir,'*.txt']);
filenames = {dirInfo.name};
N = numel(filenames);
data=cell(N,1);
for i=1:N
fid = fopen([myDir,filenames{i}] );
data{i} = textscan(fid,'%f %f','headerlines',2);
fclose(fid);
temp1=data{i,1};
time=temp1{1};
level=temp1{2};
Average(i)=mean(level(1:find(time>60)));
AverageVec=ones(length(time),1).*Average(i);
Standard=std(level);
figure(i);
plot(time,level);
xlim([0 60]);
hold on
plot(time, AverageVec);
hold on
plot(time, Standard);
legend('Level','Average','Standard Deviation')
end
the main problam with this code is that i get only average over all the 60 sec not moving average, and the standard deviation returns nothing.
few things you need to know:
*temp1 is 1x2 cell
*time and level are 22973x1 double.
Apperently you need an alternative to movmean and movstd since they where introduced in 2016a. I combined the suggestion from #bla with two loops that correct for the edge effects.
function [movmean,movstd] = moving_ms(vec,k)
if mod(k,2)==0,k=k+1;end
L = length(vec);
movmean=conv(vec,ones(k,1)./k,'same');
% correct edges
n=(k-1)/2;
movmean(1) = mean(vec(1:n+1));
N=n;
for ct = 2:n
movmean(ct) = movmean(ct-1) + (vec(ct+n) - movmean(ct-1))/N;
N=N+1;
end
movmean(L) = mean(vec((L-n):L));
N=n;
for ct = (L-1):-1:(L-n)
movmean(ct) = movmean(ct+1) + (vec(ct-n) - movmean(ct+1))/N;
N=N+1;
end
%mov variance
movstd = nan(size(vec));
for ct = 1:n
movstd(ct) = sum((vec(1:n+ct)-movmean(ct)).^2);
movstd(ct) = movstd(ct)/(n+ct-1);
end
for ct = n+1:(L-n)
movstd(ct) = sum((vec((ct-n):(ct+n))-movmean(ct)).^2);
movstd(ct) = movstd(ct)/(k-1);
end
for ct = (L-n):L
movstd(ct) = sum((vec((ct-n):L)-movmean(ct)).^2);
movstd(ct) = movstd(ct)/(L-ct+n);
end
movstd=sqrt(movstd);
Someone with matlab >=2016a can compare them using:
v=rand(1,1E3);m1 = movmean(v,101);s1=movstd(v,101);
[m2,s2] = moving_ms(v,101);
x=1:1E3;figure(1);clf;
subplot(1,2,1);plot(x,m1,x,m2);
subplot(1,2,2);plot(x,s1,x,s2);
It should show a single red line since the blue line is overlapped.

Creating a geoTIFF from an image in Matlab

I'm trying to create a geoTIFF file in Matlab from the attached png.
example image
I'm following the example provided in:
https://uk.mathworks.com/help/map/examples/exporting-images-and-raster-grids-to-geotiff.html
but need to create georeferencing information from scratch, so using makerefmat and worldfilewrite to acheive this. The code below does not cause a crash, but generates a TIFF that image readers seem to struggle with, so I assume I'm doing something wrong. There may also be some redundancy as I haven't worked with TIFF tags before. Any help appreciated!
% Load image without georeferencing
RGB = imread('uk_dT.png');
% Create worldfile for image. At present this is done by first creating a
% reference matrix, then using these values to generate a worldfile.
% Longitude spans -17:10 (west to east), latitude 63:47 (north to south)
lonmin = -17; lonmax = 10; latmin = 47; latmax = 63;
DX = (lonmax-lonmin)/(length(RGB(1,:,1))); DY = (latmin-latmax)/(length(RGB(:,1,1)));
R = makerefmat(lonmin, latmax, DX, DY);
worldfilewrite(R,'uk_dT.tfw');
% Read worldfile, create geotiff
REF = worldfileread('uk_dT.tfw','geographic',size(RGB));
geotiffwrite('uk_dT.tif',RGB,REF)
Out of interest, this code was improved for me on another forum. The result still doesn't open in some image viewers, but I think that's to do with the class of the data. As I'm writing for GIS software this solution works for me.
file = 'uk_dT.png' ;
[path,name,ext] = fileparts(file) ;
I = imread(file) ;
lonmin = -17; lonmax = 10; latmin = 47; latmax = 63;
% Write to geotiff
R = georasterref('RasterSize',size(I),'LatitudeLimits', [latmin,latmax],'LongitudeLimits',[lonmin,lonmax]);
tiffile = strcat(name,'.tif') ;
geotiffwrite(tiffile,I,R)

Matlab get vector of specific pixels

I am pretty new to Matlab and encountered a problem when working with images.
I want to get a pixel that is in a specific colour (blue) in the following image:
image
My current code looks something like this:
function p = mark(image)
%// display image I in figure
imshow(image);
%// first detect all blue values higher 60
high_blue = find(image(:,:,3)>60);
%cross elements is needed as an array later on, have to initialize it with 0
cross_elements = 0;
%// in this iteration the marked values are reduced to the ones
%where the statement R+G < B+70 applies
for i = 1:length(high_blue)
%// my image has the size 1024*768, so to access the red/green/blue values
%// i have to call the i-th, i+1024*768-th or i+1024*768*2-th position of the "array"
if ((image(high_blue(i))+image(high_blue(i)+768*1024))<...
image(high_blue(i)+2*768*1024)+70)
%add it to the array
cross_elements(end+1) = high_blue(i);
end
end
%// delete the zero element, it was only needed as a filler
cross_elements = cross_elements(cross_elements~=0);
high_vector = zeros(length(cross_elements),2);
for i = 1:length(cross_elements)
high_vector(i,1) = ceil(cross_elements(i)/768);
high_vector(i,2) = mod(cross_elements(i), 768);
end
black = zeros(768 ,1024);
for i = 1:length(high_vector)
black(high_vector(i,2), high_vector(i,1)) = 1;
end
cc = bwconncomp(black);
a = regionprops(cc, 'Centroid');
p = cat(1, a.Centroid);
%// considering the detection of the crosses:
%// RGB with B>100, R+G < 100 for B<150
%// consider detection in HSV?
%// close the figure
%// find(I(:,:,3)>150)
close;
end
but it is not optimized for Matlab, obviously.
So i was wondering if there was a way to search for pixels with specific values,
where the blue value is larger than 60 (not hard with the find command,
but at the same time the values in the red and green area not too high.
Is there a command I am missing?
Since English isn't my native language, it might even help if you gave me some suitable keywords for googling ;)
Thanks in advance
Based on your question at the end of the code, you could get what you want in a single line:
NewImage = OldImage(:,:,1) < SomeValue & OldImage(:,:,2) < SomeValue & OldImage(:,:,3) > 60;
imshow(NewImage);
for example, where as you see you provide a restriction for each channel using logical operators, that you can customize of course (eg. using | as logical OR). Is this what you are looking for? According to your code you seem to be looking for specific regions in the image like crosses or coins is that the case? Please provide more details if the code I gave you is completely off the track :)
Simple example:
A = imread('peppers.png');
B = A(:,:,3)>60 & A(:,:,2)<150 & A(:,:,1) < 100;
figure;
subplot(1,2,1);
imshow(A);
subplot(1,2,2)
imshow(B);
Giving this:

Reading data from a Text File into Matlab array

I am having difficulty in reading data from a .txt file using Matlab.
I have to create a 200x128 dimension array in Matlab, using the data from the .txt file. This is a repetitive task, and needs automation.
Each row of the .txt file is a complex number of form a+ib, which is of form a[space]b. A sample of my text file :
Link to text file : Click Here
(0)
1.2 2.32222
2.12 3.113
.
.
.
3.2 2.22
(1)
4.4 3.4444
2.33 2.11
2.3 33.3
.
.
.
(2)
.
.
(3)
.
.
(199)
.
.
I have numbers of rows (X), inside the .txt file surrounded by brackets. My final matrix should be of size 200x128. After each (X), there are exactly 128 complex numbers.
Here is what I would do. First thing, delete the "(0)" types of lines from your text file (could even use a simple shells script for that). This I put into the file called post2.txt.
# First, load the text file into Matlab:
A = load('post2.txt');
# Create the imaginary numbers based on the two columns of data:
vals = A(:,1) + i*A(:,2);
# Then reshape the column of complex numbers into a matrix
mat = reshape(vals, [200,128]);
The mat will be a matrix of 200x128 complex data. Obviously at this point you can put a loop around this to do this multiple times.
Hope that helps.
You can read the data in using the following function:
function data = readData(aFilename, m,n)
% if no parameters were passed, use these as defaults:
if ~exist('aFilename', 'var')
m = 128;
n = 200;
aFilename = 'post.txt';
end
% init some stuff:
data= nan(n, m);
formatStr = [repmat('%f', 1, 2*m)];
% Read in the Data:
fid = fopen(aFilename);
for ind = 1:n
lineID = fgetl(fid);
dataLine = fscanf(fid, formatStr);
dataLineComplex = dataLine(1:2:end) + dataLine(2:2:end)*1i;
data(ind, :) = dataLineComplex;
end
fclose(fid);
(edit) This function can be improved by including the (1) parts in the format string and throwing them out:
function data = readData(aFilename, m,n)
% if no parameters were passed, use these as defaults:
if ~exist('aFilename', 'var')
m = 128;
n = 200;
aFilename = 'post.txt';
end
% init format stuff:
formatStr = ['(%*d)\n' repmat('%f%f\n', 1, m)];
% Read in the Data:
fid = fopen(aFilename);
data = fscanf(fid, formatStr);
data = data(1:2:end) + data(2:2:end)*1i;
data = reshape(data, n,m);
fclose(fid);