Why get_full_filename error happens in matlab? - image

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));

Related

Load png files from a folder using tensorflow and print name of each image before decoding

I have a folder of images (png). I am trying to load them using tensforlow and decode the images.
import tensorflow as tf
filename_queue = tf.train.string_input_producer(
tf.train.match_filenames_once("/Users/cf/*.png"))
image_reader = tf.WholeFileReader()
_, image_file = image_reader.read(filename_queue)
image = tf.image.decode_jpeg(image_file)
with tf.Session() as sess:
tf.initialize_all_variables().run()
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
image_tensor = sess.run([image])
print(image_tensor)
coord.request_stop()
coord.join(threads)
I am getting the error:
INFO:tensorflow:Error reported to Coordinator: <class .
'tensorflow.python.framework.errors_impl.FailedPreconditionError'>,
Attempting to use uninitialized value matching_filenames_1
[[{{node matching_filenames_1/read}} =
Identity[T=DT_STRING,
_device="/job:localhost/replica:0/task:0/device:CPU:0"] .
(matching_filenames_1)]]
How do I individually print name of each image and then the size of the image using Tensorflow.
I think you are getting above error because of below line:
tf.initialize_all_variables().run()
Replace it with tf.local_variables_initializer().run()
And, use below code to print each image's name, shape and path:
all_images_paths = tf.train.match_filenames_once("./data/test/green/*.jpg")
filename_queue = tf.train.string_input_producer(all_images_paths)
image_reader = tf.WholeFileReader()
key, image_file = image_reader.read(filename_queue)
image = tf.image.decode_jpeg(image_file)
with tf.Session() as sess:
sess.run(tf.local_variables_initializer())
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
img_paths = sess.run(all_images_paths)
# get number of images in the folder
n_images = len(img_paths)
# loop through all images
for i in range(n_images):
imgf, k, img = sess.run([image_file, key, image])
image_name = k.decode("utf-8").split('\\')[-1]
# print image name, shape and path
print(image_name, img.shape, k.decode("utf-8"))
coord.request_stop()
coord.join(threads)
Sample output:
image_06741.jpg (654, 500, 3) .\data\test\green\image_06741.jpg
image_06773.jpg (500, 606, 3) .\data\test\green\image_06773.jpg
image_06751.jpg (500, 666, 3) .\data\test\green\image_06751.jpg

decode TFRecord fail. Expected image (JPEG, PNG, or GIF), got unknown format starting with '\257\

I encoded some images to TFRecords as an example and then try to decode them. However, there is a bug during the decode process and I really cannot fix it.
InvalidArgumentError: Expected image (JPEG, PNG, or GIF), got unknown format starting with '\257\222\244\257\222\244\260\223\245\260\223\245\262\225\247\263'
[[{{node DecodeJpeg}}]] [Op:IteratorGetNextSync]
encode:
def _bytes_feature(value):
"""Returns a bytes_list from a string / byte."""
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _float_feature(value):
"""Returns a float_list from a float / double."""
return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))
def _int64_feature(value):
"""Returns an int64_list from a bool / enum / int / uint."""
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
src_path = r"E:\data\example"
record_path = r"E:\data\data"
sum_per_file = 4
num = 0
key = 3
for img_name in os.listdir(src_path):
recordFileName = "trainPrecipitate.tfrecords"
writer = tf.io.TFRecordWriter(record_path + recordFileName)
img_path = os.path.join(src_path, img_name)
img = Image.open(img_path, "r")
height = np.array(img).shape[0]
width = np.array(img).shape[1]
img_raw = img.tobytes()
example = tf.train.Example(features = tf.train.Features(feature={
'image/encoded': _bytes_feature(img_raw),
'image/class/label': _int64_feature(key),
'image/height': _int64_feature(height),
'image/width': _int64_feature(width)
}))
writer.write(example.SerializeToString())
writer.close()
decode:
import IPython.display as display
train_files = tf.data.Dataset.list_files(r"E:\data\datatrainPrecipitate.tfrecords")
train_files = train_files.interleave(tf.data.TFRecordDataset)
def decode_example(example_proto):
image_feature_description = {
'image/height': tf.io.FixedLenFeature([], tf.int64),
'image/width': tf.io.FixedLenFeature([], tf.int64),
'image/class/label': tf.io.FixedLenFeature([], tf.int64, default_value=3),
'image/encoded': tf.io.FixedLenFeature([], tf.string)
}
parsed_features = tf.io.parse_single_example(example_proto, image_feature_description)
height = tf.cast(parsed_features['image/height'], tf.int32)
width = tf.cast(parsed_features['image/width'], tf.int32)
label = tf.cast(parsed_features['image/class/label'], tf.int32)
image_buffer = parsed_features['image/encoded']
image = tf.io.decode_jpeg(image_buffer, channels=3)
image = tf.cast(image, tf.float32)
return image, label
def processed_dataset(dataset):
dataset = dataset.repeat()
dataset = dataset.batch(1)
dataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
# print(dataset)
return dataset
train_dataset = train_files.map(decode_example)
# train_dataset = processed_dataset(train_dataset)
print(train_dataset)
for (image, label) in train_dataset:
print(repr(image))
InvalidArgumentError: Expected image (JPEG, PNG, or GIF), got unknown format starting with '\257\222\244\257\222\244\260\223\245\260\223\245\262\225\247\263'
[[{{node DecodeJpeg}}]] [Op:IteratorGetNextSync]
I can use tf.io.decode_raw() to decode the TFRecords and then use tf.reshape() to get the original image. While still don't know when to use tf.io.decode_raw() and when to use tf.io.decode_jpeg().

matlab imwrite new image instead of overriding it

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...

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.

how to read images from a specified folder in matlab

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

Resources