how to read images from a specified folder in matlab - image

myPath= 'C:\Users\Prienka\Documents\MATLAB\frames';
a =dir(fullfile(myPath,'*.png'));
a(1).name
a(end).name
Im1 = imread(a(1).name);
Im2 = imread(a(end).name);
Im1 = rgb2gray(Im1);
Im2 = rgb2gray(Im2);
hn1 = imhist(Im1)./numel(Im1); %initial pixel postion
hn2 = imhist(Im2)./numel(Im2); %final pixel position
d = sum(sqrt(hn2-hn1).^2);
d=sprintf('%.0f',d);
obj = VideoReader('traffic.mp4')
x=obj.FrameRate
velocity=d/x;
velocity=sprintf('%.0f',velocity)
if velocity >= 63
msgbox('SPEED EXCEEDED' )
end
this is my code for calculating the velocity of a vehicle in a vedio... the problem is i have extracted all the movie frames in a different folder named "frames"... here whenever m trying to run the code its showing a error like this
"Error using imread (line 350)
File "001.png" does not exist.
Error in pikz (line 5)
Im1 = imread(a(1).name);"
my file name is pikz.m

In your current working directory (pwd) the file does not exist. Dir only returns relative path like '001.png'. You have to use fullfile to get the absolute path like 'C:\Users\Prienka\Documents\MATLAB\frames\001.png' to pass it to imread

Related

Display a .TIF file into a tk.canvas using the PIL library

I'm actually trying to display a .tif image within a canva. However, when i launch the script, the canvas is empty. Here is the function in which i'm trying to display the .tif image in a canvas :
def display_sem_data():
global sem_data_path
global sem_photo
global current_sem_image_index
global sem_images
global sem_data_path
global sem_canvas
# Affectation of new sem_data_path with the selected sample name
sem_data_path = sem_data_path + selected_sample
#Checking if there is any SEM folder for this sample
if not os.path.isdir(sem_data_path):
# If not, display "No SEM data found" in the canvas
NoSEMDataCanvas = tk.Canvas(SEMFrame, height=40, width=900)
NoSEMDataCanvas.grid(row=0, column=0, sticky='nsew')
NoSEMDataCanvas.create_text(
450, 20, text="No data folder found for this sample, please make sure to create your sample folder at this directory :\n"+sem_data_path)
return
# Get list of all SEM images in the folder
sem_images = [image for image in os.listdir(
sem_data_path) if image.endswith(".tif")]
#Checking if there is any SEM data (.tif files) for this sample
if len(sem_images) == 0:
NoSEMDataCanvas = tk.Canvas(SEMFrame, height=40, width=900)
NoSEMDataCanvas.grid(row=0, column=0, sticky='nsew')
NoSEMDataCanvas.create_text(
450, 20, text="No SEM data found, please make sure your .tif file is in your sample folder at this directory :\n"+sem_data_path)
return
# Create a canvas to display the SEM images
sem_canvas = tk.Canvas(SEMFrame, width=800, height=600)
sem_canvas.grid(row=0, column=0)
# Create a variable to keep track of the current image index
current_sem_image_index = tk.IntVar()
current_sem_image_index.set(0)
# Display the first image on the canvas
print(sem_data_path + "\\" + sem_images[current_sem_image_index.get()])
current_sem_image = Image.open(sem_data_path + "\\" +
sem_images[current_sem_image_index.get()])
current_sem_image = current_sem_image.resize((640, 512), Image.ANTIALIAS)
sem_photo = ImageTk.PhotoImage(current_sem_image)
sem_canvas.create_image(400, 300, image=sem_photo)
# Create a scale widget to change the current image index
sem_image_index_scale = tk.Scale(SEMFrame, from_=0, to=len(
sem_images)-1, orient='horizontal', variable=current_sem_image_index, command=update_sem_image())
sem_image_index_scale.grid(row=1, column=0, sticky='ew')
I tried to modify the canvas size, the point of the image creation within the canvas, but nothing works.
I verified my directories (which are correct), as well as the files name after their acquisitions (which are also correct).
The .tif image i'm trying to load first is named "221124-c_2-1.tif" and its size is exactly 1280x1024 and weight 1.25 Mo
I would like the image to show up within the canvas.
Then, with a cursor, i'll be able to navigate between all .tif images within the same folder.

Tensorflow: Best way of creating training data with float as label

I want to use tensorflow version 2.4.0-dev20201009 in python 3.7.
My dataset are in the subfolder "data\Images". The label of an image is a float number between 1 and 5 and can read from the allTestData.csv from the subfolder "data".
What is the best way to read the data with validation split of 30 percent? So far I wanted to use
tf.keras.preprocessing.image_dataset_from_directory but this doesn't help me to incorperate the labels correctly, as all my images are in one folder and do not have one-hot encoded vectors as labels. How would you do this in tensorflow?
For the sake of completeness, I planed to use
def create_model():
model = keras.Sequential()
model.add(MobileNetV2(input_shape=(224, 224, 3), include_top=False))
model.trainable = True
model.add(layers.GlobalAveragePooling2D())
model.add(layers.Dense(1024, activation="relu"))
model.add(layers.Dense(1, activation="softmax"))
model.compile(optimizer='adam',
loss=tf.losses.mean_squared_error,
metrics=[tf.metrics.SparseCategoricalAccuracy()])
model.summary()
return model
for training the model. The question is only regarding how to read the training data?
I will answer my own question.
The best way was to write a manual function that reads the labels and images.
Assume that the images are in 'data\Images' and the labels are in a .txt file and the labels are in a .txt file at 'data\train_test_files\All_labels.txt'. Then the following two methods will do the job:
def loadImages(IMG_SIZE):
path = os.path.join(os.getcwd(), 'data\\Images')
training_data=[]
labelMap = getLabelMap()
for img in os.listdir(path):
out_array = np.zeros((350,350, 3), np.float32) #350x350 is the pixel size of the images
try:
img_array = cv2.imread(os.path.join(path, img))
img_array=img_array.astype('float32')
out_array = cv2.normalize(img_array, out_array, 0, 1, cv2.NORM_MINMAX)
out_array = cv2.resize(out_array, (IMG_SIZE, IMG_SIZE)
training_data.append([out_array, float(labelMap[img])])
except Exception as e:
pass
return training_data
def getLabelMap():
map = {}
path = os.getcwd()
path = os.path.join(path, "data\\train_test_files\\All_labels.txt")
f = open(path, "r")
for line in f:
line = line.split() #lines in txt file are of the form 'image_name.jpg 3.2'
map[line[0]] = line[1] #3.2 is the label
f.close()
return map
#call of method:
training_set=[]
training_set = loadImages(244) #I want to have my images resized to 244x244

Why get_full_filename error happens in matlab?

I want to read all images in specific folder and save it to 64*64 size jpg images.
But the error occur and I don't know why and what to do.
Pleaes help me
Error code :
File "Nikon_D70_0_19458.tif" doesn't exist
Error: imread (line 340) fullname = get_full_filename(filename);
Error: Untitled (line 13) dList(i).data = imread(dList(i).name);
My code :
clc; clear; close all;
imgPath = 'C:\Users\LG\Desktop\TIFF\dataset1\60\'; %open image path
dList = dir([imgPath '*.tif']); name = 1; %save name index
for i=1:length(dList) %open image dList(i).data = imread(dList(i).name);
dList(i).data = dList(i).data(1:256 ,1:256,:); %crop image 256*256
a = dList(i).data;
YCbCr = rgb2ycbcr(a);
Y = YCbCr(:,:,1);
Cb = YCbCr(:,:,2);
Cr = YCbCr(:,:,3);
[height,width] = size(Y);
for q=1:32:height-32
for w= 1:32:width-32
block = Y(q:q+63 , w:w+63);
Resultados='C:\Users\LG\Desktop\TIFF\training\60'; %save image path
imwrite(block, fullfile(Resultados, ['SerieN', num2str(i), '.jpg']),'Quality',60) % save image
name = name+1;
end
end
end
The field dList(i).name does not contain the full path, just the file name. You can get the full path using fullfile:
dList(i).data = imread(fullfile(imgPath, dList(i).name));

Transferring a directory contains images in RGB to grayscale

Reading the content of the directory and for every JPEG image converting to grey scale
srcFiles = dir('R:\...\images - Copy\*.jpeg');
for i = 1 : length(srcFiles)
filename = srcFiles(i).name;
try
I = imread(filename);
catch ME
continue
end
IGrey = rgb2gray(I);
imshow(IGrey);
pathOfNewFile = strcat(pathOfGSFolder,filename,'jpeg');
imwrite(IGrey,pathOfNewFile,'jpeg');
end
'R:\...\images - Copy\' is not a valid path. A folder cannot be called ...
When trying to execute the first line you will probably get an error and the variable srcFiles will be empty, so the length of this variable will be 0 and therefore the loop will not execute.

Using MATLAB to save a montage of many images as one large image file at full resolution

I am trying to save a montage of many (~500, 2MB each) images using MATLAB function imwrite, however I keep getting this error:
Error using imwrite>validateSizes (line 632)
Images must contain fewer than 2^32 - 1 bytes of data.
Error in imwrite (line 463)
validateSizes(data);
here is the code I am working with:
close all
clear all
clc
tic
file = 'ImageRegistrations.txt';
info = importdata(file);
ImageNames = info.textdata(:,1);
xoffset = info.data(:,1);
yoffset = info.data(:,2);
for i = 1:length(ImageNames);
ImageNames{i,1} = imread(ImageNames{i,1});
ImageNames{i,1} = flipud(ImageNames{i,1});
end
ImageNames = flipud(ImageNames);
for i=1:length(ImageNames)
diffx(i) = xoffset(length(ImageNames),1) - xoffset(i,1);
end
diffx = (diffx)';
diffx = flipud(diffx);
for j=1:length(ImageNames)
diffy(j) = yoffset(length(ImageNames),1) - yoffset(j,1);
end
diffy = (diffy)';
diffy = flipud(diffy);
matrix = zeros(max(diffy)+abs(min(diffy))+(2*1004),max(diffx)+abs(min(diffx))+(2*1002));
%matrix(1:size(ImageNames{1,1},1),1:size(ImageNames{1,1},2)) = ImageNames{1,1};
for q=1:length(ImageNames)
matrix((diffy(q)+abs(min(diffy))+1):(diffy(q)+abs(min(diffy))+size(ImageNames{q,1},1)),(diffx(q)+abs(min(diffx))+1):((diffx(q)+abs(min(diffx))+size(ImageNames{q,1},2)))) = ImageNames{q,1};
end
graymatrix = mat2gray(matrix);
graymatrix = flipud(graymatrix);
figure(2)
imshow(graymatrix)
imwrite(graymatrix, 'montage.tif')
toc
I use imwrite because it perserves the final montage in a full resolution file, whereas if I simply click save on the figure file it saves it as a low resolution file.
thanks!
Error does what it says on the tin, really. There is some sort of inbuilt limitation to input variable size in imwrite, and you're going over it.
Note that most images are stored as uint8 but I would guess that you end up with doubles as a result of your processing. That increases the memory usage.
It may be, therefore, that casting to another type would help. Try using im2uint8 (presuming your variable graymatrix is double, scaled between 0 and 1), before calling imwrite.

Resources