How can I read specific images from TID2013 dataset in MATLAB? I written the following code but it start from first to end of the list. The images are in this format: ixx.yy.z.bmp means xx is the number of image, yy is the model of the noise and z is the level of the noise. I just want to work with models 1,2 in level 4,5 but I don't know how to do it. please someone help me! By the way there are 25 reference images, 24 models of noise and 5 level of each model of noise that I wrote them vertically in info1.txt , info2.txt , info3.txt respectively.
clc; clear; close all;
% read Original images
cd 'C:\Users\Desktop'
for NO1 = 1:25
in1 = fopen('info1.txt');
xx = fgets(in1);
A = imread(strcat('C:\Users\Desktop\reference_images\',xx,'.bmp'));
A = rgb2gray(A);
end
% read distorted images
for NO1 = 1:25
in1 = fopen('info1.txt');
xx = fgets(in1);
for NO2 = 1:24
in2 = fopen('info2.txt');
yy = fgets(in2);
for NO3 = 1:5
in3 = fopen('info3.txt');
z = fgets(in3);
B = imread(strcat('C:\Users\Desktop\distorted_images\',xx,yy,z,'.bmp'));
B = rgb2gray(B);
C = imadjust(B);
% Write restored images
imwrite(C,['C:\Users\Desktop\restored_images\','i',sprintf('%02d',NO1),'_',sprintf('%02d',NO2),'_',num2str(NO3),'.bmp']);
end
end
end
The only thing you need to do is to change values of your for loops. Note that in matlab, in contrast with most other languages, for-loops are not restricted to specific step length and can be any vectors.
imageNames = textread('info1.txt', '%s');
noiseModels = textread('info2.txt', '%s');
noiseLevels = textread('info3.txt', '%s');
imageIndices = 1:25;
modelIndices = [1, 2, 7:8];
levelindices = [4 5];
sourceDir = 'C:\Users\Desktop\distorted_images\';
destDir = 'C:\Users\Desktop\restored_images\';
for ii = imageIndices
name = imageNames{ii};
for jj = modelIndices
model = noiseModels{jj};
for kk = levelindices
level = noiseLevels{kk};
sourcePath = sprintf('%s%s%s%s.bmp', sourceDir, name, model, level)
destPath = sprintf('%si%02d_%02d_%02d.bmp', destDir, ii, jj, kk)
B = imread(sourcePath);
B = rgb2gray(B);
C = imadjust(B);
imwrite(C, destPath);
end
end
end
Related
I'm planning to plot a graph of velocity against time using matlab. The change of time is 0.05 and total time 15. When time change, the graph will change and save a figure of that. I had mat file which contained all the data for time and velocity.
E.g, t=0, v=0, plot and save, t=0.05, v=1, plot and save until t=15.
I tried to use v=v+1 (which acts like i++) but failed to read the value of v in 2nd row. Any other method to do so?
Thank You.
The code is
i = 001
dt = t(2,1) - t(1,1);
k = dt*(i-1);
filename1 = 'front_data';
matFileName = sprintf('%s.mat', filename1);
matData = load(matFileName);
t = matData.time;
fv = matData.front_velocity;
fig = figure%('visible', 'off');
s = t(1,1);
fv = fv(1,1);
lot (s,fv,'*')
pic_filename = sprintf('front_data%02d.jpeg', k);
print(fig,pic_filename,'-djpeg')
istart = 002
iend = 301
for i = istart:iend
k = dt*(i-1);
t = t+dt
filename1 = 'front_data';
matFileName = sprintf('%s.mat', filename1);
matData = load(matFileName);
t = matData.time;
fv = matData.front_velocity;
v = fv(1,1);
v = v+1;
h = figure
axis([0 15 0 0.6])
plot(t,v,'*')
pic_filename = sprintf('front_data%02d.jpeg', k);
print(h,pic_filename,'-djpeg')
end
And the example I refer is the [https://www.mathworks.com/matlabcentral/answers/110632-how-to-increment-a-variable]
I reduced your example to the essential parts.
istart = 2;
iend = 301;
counter=istart;
%load data
% filename1 = 'front_data';
% matFileName = sprintf('%s.mat', filename1);
% matData = load(matFileName);
% t = matData.time;
% fv = matData.front_velocity;
%for demonstaration
t=0:.05:15;
fv=rand(size(t));
for i = istart:iend
%update
time = t(istart:counter);
values = fv(istart:counter);
%plot
plot(time,values,'*')
%increase index
counter=counter+1;
end
As you are loading always the same data in the loop you can do it once outside the loop, and for plotting you just update the length of your vector to be plotted. You could also just append the new value to the actual list.
I'm writing the code in Matlab to find interest point using DoG in the image.
Here is the main.m:
imTest1 = rgb2gray(imread('1.jpg'));
imTest1 = double(imTest1);
sigma = 0.6;
k = 5;
thresh = 3;
[x1,y1,r1] = DoG(k,sigma,thresh,imTest1);
%get the interest points and show it on the image with its scale
figure(1);
imshow(imTest1,[]), hold on, scatter(y1,x1,r1,'r');
And the function DoG is:
function [x,y,r] = DoG(k,sigma,thresh,imTest)
x = []; y = []; r = [];
%suppose 5 levels of gaussian blur
for i = 1:k
g{i} = fspecial('gaussian',size(imTest),i*sigma);
end
%so 4 levels of DoG
for i = 1:k-1
d{i} = imfilter(imTest,g{i+1}-g{i});
end
%compare the current pixel in the image to the surrounding pixels (26 points),if it is the maxima/minima, this pixel will be a interest point
for i = 2:k-2
for m = 2:size(imTest,1)-1
for n = 2:size(imTest,2)-1
id = 1;
compare = zeros(1,27);
for ii = i-1:i+1
for mm = m-1:m+1
for nn = n-1:n+1
compare(id) = d{ii}(mm,nn);
id = id+1;
end
end
end
compare_max = max(compare);
compare_min = min(compare);
if (compare_max == d{i}(m,n) || compare_min == d{i}(m,n))
if (compare_min < -thresh || compare_max > thresh)
x = [x;m];
y = [y;n];
r = [r;abs(d{i}(m,n))];
end
end
end
end
end
end
So there's a gaussian function and the sigma i set is 0.6. After running the code, I find the position is not correct and the scales looks almost the same for all interest points. I think my code should work but actually the result is not. Anybody know what's the problem?
The following code correctly loads an mp4 file and stores it in a 3D matrix.
r = 1;
fileName = testDummyMP4;
readerobj = VideoReader(fileName, 'tag', 'myreader1');
F = get(readerobj, 'numberOfFrames');
tampon = single(read(readerobj,1));
tampon = imresize(tampon(:,:,1),r);
I = zeros(size(tampon,1),size(tampon,2),F,'uint8');
for k = 1:F
disp(['Open: ' num2str(round(100*k/F)) '%'])
vidFrames = single(read(readerobj,k));
I(:,:,k) = imresize(vidFrames(:,:,2),r);
end;
imagesc((I(:,:,1)));
This is the output
I'm trying to reverse engineer this code so that it produces the same sort of result for but for a .raw 8bit rbg file. Following the answers from this question I tried the following:
You can download the 'M1302000245_1436389857.982603.raw' rbg file here
Or Google Drive version here
Ix = 256;
Iy = 256;
SF = 30; % Sample frequency
RecordingTime = 30;
Iz = SF*RecordingTime
testDummy = 'M1302000245_1436389857.982603.raw'
fin = fopen(testDummy, 'r');
I = fread(fin, Ix*Iy*3*Iz, 'uint8');
fclose(fin);
I = reshape(I, [Ix Iy 3 Iz]); % The rbg should be 256x256x3x900
% I've tried each of the following manipulations before calling imagesc to no avail
% I = flipdim(imrotate(I, -90),2);
% I=impixel(I)
% I=I'
imagesc((I(:,:,1))); % view first slice
This gives:
What am I doing wrong?
Additional info:
Recordings are taken using raspberry pi cameras with the following python code
class BrainCamera:
def __init__(self):
self.video_format = "rgb"
#self.video_quality = 5
# Set up the settings of the camera so that
# Exposure and gains are constant.
self.camera = picamera.PiCamera()
self.camera.resolution = (256,256)
self.camera.framerate = 30
sleep(2.0)
self.camera.shutter_speed = self.camera.exposure_speed
self.camera.exposure_mode = 'off'
g = self.camera.awb_gains
self.camera.awb_mode = 'off'
self.camera.awb_gains = g
self.camera.shutter_speed = 30000
self.camera.awb_gains = (1,1)
def start_recording(self, video_name_path):
self.camera.start_recording(video_name_path, format=self.video_format)
self.camera.start_preview()
def stop_recording(self):
self.camera.stop_recording()
self.camera.stop_preview()
# Destructor
def __del__(self):
print ("Closed Camera")
self.camera.close()
I don't get the output you have, but I get some reasonable image:
%your vode from above, ending with I=fread(...)
I=uint8(I)
I2=reshape(I, 3, Ix ,Iy, []);
I2=permute(I2,[3,2,1,4]);
imagesc(I2(:,:,:,1));
implay(I2);
With Daniel's help I got the following working. Additionally a co-worker found out how to get the number of frames of a .raw rbg video. This we needed since it turns out assuming noFrame = SF*RecordingTime was a bad idea.
testDummy = 'M1302000245_1436389857.982603.raw'
testDummyInfo = dir(testDummy);
noFrames = testDummyInfo.bytes/(256*256*3); % In my question Iz = noFrames
fin = fopen(testDummy, 'r');
I = fread(fin, testDummyInfo.bytes, 'uint8');
fclose(fin);
I=uint8(I);
I2=reshape(I, 3, Ix ,Iy, noFrames);
I2=permute(I2,[3,2,1,4]);
imagesc(I2(:,:,2,1)); % Throw out unnecessarry channels r and b. Only want GFP signal
to produce:
Hi I would like to save numerical data from an operation inside a loop. Lets see my segmentation example:
clear all, clc;
a=1:35;
A = arrayfun( #(x) sprintf( '%04d', x ), a, 'UniformOutput', false );
I = cellfun( #(b) imread( ['C:Teste/' b '/c1/' b '.png'] ), A, 'UniformOutput', false );
for i = a
% Gaussian Filter
W = fspecial('gaussian',[10,10],2);
J = imfilter(I,W);
% Finding Circular objects -- Houng Transform
[centers, radii, metric] = imfindcircles(J,[5 10], 'Sensitivity',0.93,'Edge',0.27);
idx_mask = ones(size(radii));
min_dist = 2; % relative value.
for i = 2:length(radii)
cur_cent = centers(i, :);
for j = 1:i-1
other_cent = centers(j,:);
x_dist = other_cent(1) - cur_cent(1);
y_dist = other_cent(2) - cur_cent(2);
if sqrt(x_dist^2+y_dist^2) < min_dist*(radii(i) + radii(j)) && idx_mask(j) == 1
idx_mask(i) = 0;
break
end
end
end
idx_mask = logical(idx_mask);
centers_use = centers(idx_mask, :);
radii_use = radii(idx_mask, :);
metric_use = metric(idx_mask, :);
viscircles(centers_use, radii_use,'EdgeColor','b');
a=length(centers_use)
end
So the point is to save the 35 results in one column of an xls file.
I was trying to do this but only the last element of the loop is printed in the exel file...
filename = 'testdata.xlsx';
A = vertcat('Test', 'Results', num2cell(a'));
sheet = 1;
xlRange = 'F03';
xlswrite(filename,A,sheet,xlRange)
Can please anyone help me out? I know there many questions related to this one but none of them covers my issue...
I will leave here one image for testing:
Thanks a lot in advance.
John
As #excaza said, you need to expand b
a=1:35;
for i = a
b=10+a;
end
filename = 'testdata.xlsx';
A = vertcat('Example', 'Results', num2cell(b'));
sheet = 1;
xlRange = 'B1';
xlswrite(filename,A,sheet,xlRange)
I am currently writing a code in matlab to analyze the optical flow in leach hearts and for some reason, whenever I run this it returns weird complex functions. I'm not sure where they come from and I would love some help on figuring that out.
function [opticalFlow] = opticalflowanalysis(handles,hOpticalflow)
videoReader = vision.VideoFileReader('jun07_0165_segment8to12_20.avi','ImageColorSpace','Intensity','VideoOutputDataType','single');
converter = vision.ImageDataTypeConverter;
opticalFlow = vision.OpticalFlow('OutputValue', 'Horizontal and vertical components in complex form','ReferenceFrameDelay', 6);
shapeInserter = vision.ShapeInserter('Shape','Lines','BorderColor','Custom', 'CustomBorderColor', 255);
videoPlayer = vision.VideoPlayer('Name','Motion Vector');
%Convert the image to single precision, then compute optical flow for the video. Generate coordinate points and draw lines to indicate flow.
i=0;
mm = ones(1080,1920);
%Display results.
while ~isDone(videoReader)
frame = step(videoReader);
im = step(converter, frame);
of = step(opticalFlow, im); %always complex number
aa = size(of)
lines = videooptflowlines(of, 5); %complex number only sometimes - when lines appear?
bb = size(lines)
x = i+ 1;
if(x==2)
mm = of;
end
% show diff bw of and lines matrices
if (x == 2)||(x == 10)
for j=1:1:1080 %gives j = [1 2 ... 720]
for k=1:1:1920 %gives k = [1 2 ... 1280]
of(j,k)
lines(j,k)
if(of(j,k) ~= lines(j,k))
disp(['of[',num2str(j),',',num2str(k),'] = ', num2str(of(j,k)), '...', 'lines[',num2str(j),',',num2str(k),'] = ', num2str(lines(j,k))])
end
end
end
end
if ~isempty(lines)
out = step(shapeInserter, im, lines);
step(videoPlayer, out);
end
end
%Close the video reader and player ,
%handles.output = hObject;
release(videoPlayer);
release(videoReader);
mm
It returns:
aa =
1080 1920
bb =
36465 4
Where do the variables from bb come from?
Thanks,
Jacob
Try putting semi-colons (ie ;) at the ends of the lines in which aa and bb are assigned to
aa = size(of);
...
bb = size(lines);
and see what happens.
Mind you, since neither aa nor bb seems to be used later in the program you could probably safely delete both those lines.