I'm trying to create an image array and save it into a variable called manosData. I already tried this code
myFolder = 'C:\MATLAB\fotos';
filePattern = fullfile(myFolder, '*.jpg');
jpegFiles = dir(filePattern);
manosData = cell(1,numel(jpegFiles));
for k = 1:length(jpegFiles)
baseFileName = jpegFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
imageArray64x64 = imread(fullFileName);
imageArray64x64New = imresize(imageArray64x64, [64 64]);
manosData{k} = imageArray64x64New;
end
%Save
But when i try to plot my 8 images, i just get a blank window. This is the code am using for that:
load manosData
for j=1:9
subplot(3,3,j)
end
Thanks, Cath.
Try instead:
load manosData
for j=1:9
subplot(3,3,j)
image(manosData{j})
end
the command subplot just creates a subaxis to the current figure. You need to apply a plotting command, for example image, plot, or line to draw any content to the axes.
Related
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
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));
I have function that checks for bottle cap. If there is no cap detected, it writes it as an image into folder. My problem is that if I pass different image, the old one get overridden with new one, is there a way to make new image instead of overwriting old one such as nocap0,jpg, then new one nocap1.jpg etc?
Code:
function [ ] = CHECK_FOR_CAP( image )
%crop loaction of cap
imageCROP = imcrop(image,[130 0 100 50]);
%turn to BW
imageBW=im2bw(imageCROP);
%count black pixels
answer = sum(sum(imageBW==0));
%if <250 black, save it to folder NOCAP
if answer<250
imwrite(image, 'TESTINGFOLDERS/NOCAP/nocap.jpg', 'jpg');
disp('NO CAP DETECTED');
end
UPDATE
I changed the code a bit now. Everytime I give a different image it now writes new one, BUT it overwrites the previous one aswell like so: http://imgur.com/a/KIuvg
My new code:
function [ ] = CHECK_FOR_CAP( image )
folder = 'TESTINGFOLDERS/NOCAP';
filePattern = fullfile(folder, '/*.*');
ImageFiles = dir(filePattern);
%crop loaction of cap
imageCROP = imcrop(image,[130 0 100 50]);
%turn to BW
imageBW=im2bw(imageCROP);
%count black pixels
answer = sum(sum(imageBW==0));
%if <250 black, save it to folder NOCAP
if answer<250
a = length(ImageFiles)-1;
for j = 1:a
baseFileName = [num2str(j),'.jpg'];
filename = fullfile(folder,baseFileName);
if exist(filename,'file')
imwrite(image,filename);
end
imwrite(image, fullfile(filename));
end
disp('NO CAP DETECTED');
end
You write
for j = 1:a
baseFileName = [num2str(j),'.jpg'];
filename = fullfile(folder,baseFileName);
if exist(filename,'file')
imwrite(image,filename);
end
imwrite(image, fullfile(filename));
end
This means that whenever you find a file, you overwrite it. Then you overwrite it again. You do this for as many files as exist (a comes from some dir you do on your folder). What you want is the opposite: find one that does not exist. Something like this:
j = 0;
while true
j = j + 1;
baseFileName = [num2str(j),'.jpg'];
filename = fullfile(folder,baseFileName);
if ~exist(filename,'file')
break
end
end
imwrite(image, fullfile(filename));
This could be further shortened (e.g., by looping while exist(...)) but it conveys the idea...
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.
I have written this code to help me compare different image histograms however when i run it i get a figure window popping up. I can't see anywhere in the code where i have written imshow and am really confused. Can anyone see why? thanks
%ensure we start with an empty workspace
clear
myPath= 'C:\coursework\'; %#'
number_of_desired_results = 5; %top n results to return
images_path = strcat(myPath, 'fruitnveg');
images_file_names = dir(fullfile(images_path, '*.png'));
images = cell(length(images_file_names), 3);
number_of_images = length(images);
%textures contruction
%loop through all textures and store them
disp('Starting construction of search domain...');
for i = 1:length(images)
image = strcat(images_path, '\', images_file_names(i).name); %#'
%store image object of image
images{i, 1} = imread(image);
%store histogram of image
images{i, 2} = imhist(rgb2ind(images{i, 1}, colormap(colorcube(256))));
%store name of image
images{i, 3} = images_file_names(i).name;
disp(strcat({'Loaded image '}, num2str(i)));
end
disp('Construction of search domain done');
%load the three example images
RGB1 = imread('C:\coursework\examples\salmon.jpg');
X1 = rgb2ind(RGB1,colormap(colorcube(256)));
example1 = imhist(X1);
RGB2 = imread('C:\coursework\examples\eggs.jpg');
X2 = rgb2ind(RGB2,colormap(colorcube(256)));
example2 = imhist(X2);
RGB3 = imread('C:\coursework\examples\steak.jpg');
X3 = rgb2ind(RGB3,colormap(colorcube(256)));
example3 = imhist(X3);
disp('three examples loaded');
disp('compare examples to loaded fruit images');
results = cell(length(images), 2);
results2 = cell(length(images), 2);
results3 = cell(length(images), 2);
for i = 1:length(images)
results{i,1} = images{i,3};
results{i,2} = hi(example1,images{i, 2});
end
results = flipdim(sortrows(results,2),1);
for i = 1:length(images)
results2{i,1} = images{i,3};
results2{i,2} = hi(example2,images{i, 2});
end
results2 = flipdim(sortrows(results2,2),1);
for i = 1:length(images)
results3{i,1} = images{i,3};
results3{i,2} = hi(example3,images{i, 2});
end
results3 = flipdim(sortrows(results3,2),1);
The colormap function sets the current figure's colormap, if there is no figure one is created.
The second parameter of imhist should be the number of bins used in the histogram, not the colormap.
Run your code in the Matlab debugger, step through it line by line, and see when the figure window pops up. That'll tell you what's creating it.
Etienne's answer is right for why you're getting a figure, but I'd just like to add that colormap is unnecessary in this code:
images{i, 2} = imhist(rgb2ind(images{i, 1}, colormap(colorcube(256))));
All you need is:
images{i, 2} = imhist(rgb2ind(images{i, 1}, colorcube(256)));
The second input of rgb2ind should be a colormap, yes. But the output of colorcube is a colormap already. Unless you've got an existing figure and you either want to set the colormap of it or retrieve the colormap it is currently using, the actual function colormap is not necessary.
Other than opening an unnecessary figure, the output of your existing code won't be wrong, as I think in this situation colormap will just pass as an output argument the colormap it was given as an input argument. For example, if you want to set the current figure colormap to one of the inbuilts and return the actual colormap:
cmap = colormap('bone');