I am using TPU runtime in Google Colab, but having problems in reading files (not sure). I initialized TPU using:
import tensorflow as tf
import os
import tensorflow_datasets as tfds
resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='grpc://' + os.environ['COLAB_TPU_ADDR'])
tf.config.experimental_connect_to_cluster(resolver)
# This is the TPU initialization code that has to be at the beginning.
tf.tpu.experimental.initialize_tpu_system(resolver)
print("All devices: ", tf.config.list_logical_devices('TPU'))
I have many images in a folder in Google Colab storage ( e.g. '/content/train2017/000000000009.jpg'). I run the following code:
import tensorflow as tf
def load_image(image_path):
img = tf.io.read_file(image_path)
img = tf.image.decode_jpeg(img, channels=3)
img = tf.image.resize(img, (299, 299))
img = tf.keras.applications.inception_v3.preprocess_input(img)
return img, image_path
load_image('/content/train2017/000000000009.jpg')
But, I am getting the following error:
---------------------------------------------------------------------------
UnimplementedError Traceback (most recent call last)
<ipython-input-33-a7fbb45f3b76> in <module>()
----> 1 load_image('/content/train2017/000000000009.jpg')
5 frames
<ipython-input-7-862c73d29b96> in load_image(image_path)
2 img = tf.io.read_file(image_path)
3 img = tf.image.decode_jpeg(img, channels=3)
----> 4 img = tf.image.resize(img, (299, 299))
5 img = tf.keras.applications.inception_v3.preprocess_input(img)
6 return img, image_path
/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/image_ops_impl.py in resize_images_v2(images, size, method, preserve_aspect_ratio, antialias, name)
1515 preserve_aspect_ratio=preserve_aspect_ratio,
1516 name=name,
-> 1517 skip_resize_if_same=False)
1518
1519
/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/image_ops_impl.py in _resize_images_common(images, resizer_fn, size, preserve_aspect_ratio, name, skip_resize_if_same)
1183 with ops.name_scope(name, 'resize', [images, size]):
1184 images = ops.convert_to_tensor(images, name='images')
-> 1185 if images.get_shape().ndims is None:
1186 raise ValueError('\'images\' contains no shape.')
1187 # TODO(shlens): Migrate this functionality to the underlying Op's.
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py in get_shape(self)
1071 def get_shape(self):
1072 """Alias of Tensor.shape."""
-> 1073 return self.shape
1074
1075 def _shape_as_list(self):
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py in shape(self)
1065 self._tensor_shape = tensor_shape.TensorShape(self._shape_tuple())
1066 except core._NotOkStatusException as e:
-> 1067 six.raise_from(core._status_to_exception(e.code, e.message), None)
1068
1069 return self._tensor_shape
/usr/local/lib/python3.6/dist-packages/six.py in raise_from(value, from_value)
UnimplementedError: File system scheme '[local]' not implemented (file: '/content/train2017/000000000009.jpg')
How should I solve it? I found something like a gs bucket, but it is paid. Is there any other way to solve this?
Cloud TPUs can only access data in GCS as only the GCS file system is registered. Please see: https://cloud.google.com/tpu/docs/troubleshooting#cannot_use_local_filesystem for more details.
Though for checkpointing starting with TF 2.3 release you should be able to use the experimental_io_device='/job:localhost' option (https://www.tensorflow.org/api_docs/python/tf/train/CheckpointOptions) to store/load your checkpoints to and from your Colab runtime. Even with that API though you'll need to load data from GCS.
Example:
checkpoint = tf.train.Checkpoint(model=model)
local_device_option = tf.train.CheckpointOptions(experimental_io_device="/job:localhost")
checkpoint.write(checkpoint_path, options=local_device_option)
For loading file from local file when using TPU - read them as normal python file.read() (not tf.io). In your case:
def load_image(image_path):
with open(image_path, "rb") as local_file: # <= change here
img = local_file.read()
img = tf.image.decode_jpeg(img, channels=3)
img = tf.image.resize(img, (299, 299))
img = tf.keras.applications.inception_v3.preprocess_input(img)
return img, image_path
load_image('/content/train2017/000000000009.jpg')
Related
How can i load image from keras with local image ? can i ? because im getting error permission access denied?
im trying to classification image with tensorflow from local jupyter notebook.
import numpy as np
from keras.preprocessing import image
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img = image.load_img(os.getcwd()+'/tmp/test/british_cat/', target_size=(150,150))
imgplot = plt.imshow(img)
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
images = np.vstack([x])
classes = model.predict(images, batch_size=10)
# model.summary()
print(classes[0:10])
if classes[0][0]==1:
print('British Cat')
elif classes[0][1]==1:
print('Love Bird')
elif classes[0][2]==1:
print('Koi Fish')
else:
print('error')
the error is :
---------------------------------------------------------------------------
PermissionError Traceback (most recent call last)
<ipython-input-49-7b705ffefd08> in <module>
6
7
----> 8 img = image.load_img(os.getcwd()+'/tmp/test/british_cat/', target_size=(150,150))
9 imgplot = plt.imshow(img)
10 x = image.img_to_array(img)
~\miniconda3\envs\myenv\lib\site-packages\tensorflow\python\keras\preprocessing\image.py in load_img(path, grayscale, color_mode, target_size, interpolation)
298 ValueError: if interpolation method is not supported.
299 """
--> 300 return image.load_img(path, grayscale=grayscale, color_mode=color_mode,
301 target_size=target_size, interpolation=interpolation)
302
~\miniconda3\envs\myenv\lib\site-packages\keras_preprocessing\image\utils.py in load_img(path, grayscale, color_mode, target_size, interpolation)
111 raise ImportError('Could not import PIL.Image. '
112 'The use of `load_img` requires PIL.')
--> 113 with open(path, 'rb') as f:
114 img = pil_image.open(io.BytesIO(f.read()))
115 if color_mode == 'grayscale':
PermissionError: [Errno 13] Permission denied: 'c:\\Users\\AZHAR IE\\Documents\\project\\webscraping google\\Google-Image-Scraper-master/tmp/test/british_cat/
You can get the image names by "os.listdir" then you can load images one by one using for loop.
folder= "./tmp/test/british_cat/"
image_names=os.listdir(folder)
for filename in image_names:
img = tf.keras.preprocessing.image.load_img(folder+filename, target_size=(150, 150))
x=image.img_to_array(img)
x=np.expand_dims(x, axis=0)
images = np.vstack([x])
classes = model.predict(images, batch_size=10)
I was trying to split my image through 4 patches when I came through the following error:
UnimplementedError: Only support ksizes across space
iterator = tf.compat.v1.data.make_one_shot_iterator(parsed_dataset)
image,label = iterator.get_next()
image_height = image.shape[0]
image_width = image.shape[1]
# Since the expected type is (batch,height,width,channels), i have tryied to expand my image that have
# dimensions: (800,344,3) to (1,800,344,3) but didn't solved the error.
#image = tf.expand_dims(image ,0)
images = list(image)
extracted_patches = tf.image.extract_patches(images=images,
sizes=[1,int(0.25*image_height),int(0.25*image_width),3],
strides=[1,int(0.25*image_height),int(0.25*image_width),3],
rates=[1,1,1,1],
padding="SAME")
Traceback:
---------------------------------------------------------------------------
UnimplementedError Traceback (most recent call last)
<ipython-input-64-23c2aff4c306> in <module>()
17 strides=[1,int(0.25*image_height),int(0.25*image_width),3],
18 rates=[1,1,1,1],
---> 19 padding="SAME")
20
21
/Users/lucianoaraujo/anaconda2/lib/python2.7/site-packages/tensorflow_core/python/ops/array_ops.pyc in extract_image_patches_v2(images, sizes, strides, rates, padding, name)
4657 """
4658 return gen_array_ops.extract_image_patches(images, sizes, strides, rates,
-> 4659 padding, name)
4660
4661
/Users/lucianoaraujo/anaconda2/lib/python2.7/site-packages/tensorflow_core/python/ops/gen_array_ops.pyc in extract_image_patches(images, ksizes, strides, rates, padding, name)
2542 else:
2543 message = e.message
-> 2544 _six.raise_from(_core._status_to_exception(e.code, message), None)
2545 # Add nodes to the TensorFlow graph.
2546 if not isinstance(ksizes, (list, tuple)):
/Users/lucianoaraujo/anaconda2/lib/python2.7/site-packages/six.pyc in raise_from(value, from_value)
735 else:
736 def raise_from(value, from_value):
--> 737 raise value
738
739
UnimplementedError: Only support ksizes across space. [Op:ExtractImagePatches]
After further research I was able to manage by changing from:
images = list(image)
extracted_patches = tf.image.extract_patches(images=images,
sizes=[1,int(0.25*image_height),int(0.25*image_width),3],
strides=[1,int(0.25*image_height),int(0.25*image_width),3],
rates=[1,1,1,1],
padding="SAME")
To :
image = tf.expand_dims(image ,0)
extracted_patches = tf.image.extract_patches(images=image,
sizes=[1,int(0.25*image_height),int(0.25*image_width),1],
strides=[1,int(0.25*image_height),int(0.25*image_width),1],
rates=[1,1,1,1],
padding="SAME")
And then reshape to obtain 3 channel images:
patches = tf.reshape(extracted_patches,[-1,int(0.25*image_height),int(0.25*image_width),3])
I am trying to read bmp images (2048 x2048), resize them to 256x 256 and write the image to disk using tensorflow. I have succeeded in reading it but unable to find a way write it to disk. Any idea how to do it ?
Here is the code below:
import tensorflow as tf
img_path = "D:/image01.bmp"
img = tf.read_file(img_path)
img_decode = tf.image.decode_bmp(img, channels=1) # unit8 tensor
IMG_WIDTH = 256
IMG_HEIGHT = 256
img_cast = tf.cast(img_decode,dtype=tf.uint8)
img_4d = tf.expand_dims(img_cast, axis=0)
img_res = tf.image.resize_bilinear(img_4d, (IMG_HEIGHT, IMG_WIDTH), align_corners=True)
session = tf.InteractiveSession()
file_name = "D:/out.bmp"
file = tf.write_file(file_name, img_res)
print('Image Saved')
session.close()
Error:
ValueError Traceback (most recent call last)
D:\Users\ge3f-P2\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py in _apply_op_helper(self, op_type_name, name, **keywords)
509 as_ref=input_arg.is_ref,
--> 510 preferred_dtype=default_dtype)
511 except TypeError as err:
D:\Users\ge3f-P2\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in internal_convert_to_tensor(value, dtype, name, as_ref, preferred_dtype, ctx)
1145 if ret is None:
-> 1146 ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
1147
D:\Users\ge3f-P2\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in _TensorTensorConversionFunction(t, dtype, name, as_ref)
982 "Tensor conversion requested dtype %s for Tensor with dtype %s: %r" %
--> 983 (dtype.name, t.dtype.name, str(t)))
984 return t
ValueError: Tensor conversion requested dtype string for Tensor with dtype uint8: 'Tensor("DecodeBmp:0", shape=(?, ?, 1), dtype=uint8)'
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
<ipython-input-18-9b7aeb9e42de> in <module>
----> 1 file = tf.write_file(file_name,final)
D:\Users\ge3f-P2\Anaconda3\lib\site-packages\tensorflow\python\ops\gen_io_ops.py in write_file(filename, contents, name)
2256 if _ctx is None or not _ctx._eager_context.is_eager:
2257 _, _, _op = _op_def_lib._apply_op_helper(
-> 2258 "WriteFile", filename=filename, contents=contents, name=name)
2259 return _op
2260 _result = None
D:\Users\ge3f-P2\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py in _apply_op_helper(self, op_type_name, name, **keywords)
531 if input_arg.type != types_pb2.DT_INVALID:
532 raise TypeError("%s expected type of %s." %
--> 533 (prefix, dtypes.as_dtype(input_arg.type).name))
534 else:
535 # Update the maps with the default, if needed.
TypeError: Input 'contents' of 'WriteFile' Op has type uint8 that does not match expected type of string.
The problem is I can't find a "encode_bmp" or any bmp related function that can be used to encode the image and save the resized image to disk.
I went through this thread but this doesn't help solve the question.
Link here
Since Tensorflow currently does not have a native way of saving/encoding images to the BMP format, one way to solve this would be to save the image as a PNG in a temporary location and then use the Python Imaging Library to convert it to a BMP.
See: PILs Image.Save method and the list of supported file formats.
From my understanding, the reason for the exception you are receiving is that you are trying to save a unit8 tensor, when the write_file method expects an - encoded - string.
Try this:
from PIL import Image
.
.
.
file_name = "D:/tmp.png"
enc = tf.image.encode_png(img_res)
file = tf.write_file(file_name, enc)
print('PNG Image Saved')
session.close()
Image.open(file_name).save("D:/out.bmp")
os.remove(file_name)
I used a pretrained imagenet VGG16 model in keras and add my own Dense on top.
I'm trying to save and load weights from the model i have trained.
the code im using to save the model is
import time
start = time.time()
history = model.fit_generator(generator=train_batches,
epochs=epochs,
steps_per_epoch=steps_train,
#callbacks=callbacks_list,
validation_data=valid_batches,
validation_steps=steps_valid,
shuffle=True)
end = time.time()
model.save("modelvgg.npy")
Let me know if this an incorrect way to do it,or if there is a better way to do it.
but when i try to load them,using this,
def __init__(self, vgg16_npy_path=None, trainable=True):
if vgg16_npy_path is None:
path = inspect.getfile(Vgg16)
path = os.path.abspath(os.path.join(path, os.pardir))
path = os.path.join(path, "modelvgg.npy")
vgg16_npy_path = path
print(path)
self.data_dict = np.load(vgg16_npy_path, encoding='latin1').item()
self.trainable = trainable
print("npy file loaded")
but i get this error:
UnpicklingError Traceback (most recent call last)
~/.local/lib/python3.6/site-packages/numpy/lib/npyio.py in load(file, mmap_mode, allow_pickle, fix_imports, encoding)
446 try:
--> 447 return pickle.load(fid, **pickle_kwargs)
448 except Exception:
UnpicklingError: invalid load key, 'H'.
During handling of the above exception, another exception occurred:
OSError Traceback (most recent call last)
<ipython-input-5-d099900e8f3b> in <module>
46 labels = tf.placeholder(tf.float32, [batch_size, 2])
47
---> 48 vgg = vgg16.Vgg16()
49 model.build(images)
50 cost = (-1) * tf.reduce_sum(tf.multiply(labels, tf.log(model.prob)), axis=1)
~/Bureau/Grad-CAM_final/model/vgg16.py in __init__(self, vgg16_npy_path, trainable)
18 print(path)
19
---> 20 self.data_dict = np.load(vgg16_npy_path, encoding='latin1').item()
21 self.trainable = trainable
22 print("npy file loaded")
~/.local/lib/python3.6/site-packages/numpy/lib/npyio.py in load(file, mmap_mode, allow_pickle, fix_imports, encoding)
448 except Exception:
449 raise IOError(
--> 450 "Failed to interpret file %s as a pickle" % repr(file))
451 finally:
452 if own_fid:
OSError: Failed to interpret file '/home/omri/Bureau/Grad-CAM_final/model/modelvgg.npy' as a pickle
Any suggestions on what i may be doing wrong? Thank you in advance.
This is not the correct way to load a keras model saved as HDF5 (since you saved it with model.save)
self.data_dict = np.load(vgg16_npy_path, encoding='latin1').item()
The correct way is to use keras.models.load_model:
from keras.models import load_model
model = load_model('your_file.hdf5')
I am trying to execute the Tensorflow "object_detection_tutorial.py" in jupyter notebook, with my trained neural network data but it throws a ValueError. The file mentioned above is part of Sentdexs tensorflow tutorial for object detection on youtube.
You can find it here: (https://www.youtube.com/watch?v=srPndLNMMpk&list=PLQVvvaa0QuDcNK5GeCQnxYnSSaar2tpku&index=6)
My Images are of Size: 490x704. So that would result in an 344960-array.
But it sais: ValueError: cannot reshape array of size 344960 into shape (490,704,3)
What am I doing wrong?
Code:
Imports
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
Env setup
# This is needed to display the images.
%matplotlib inline
# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")
Object detection imports
from utils import label_map_util
from utils import visualization_utils as vis_util
Variables
# What model to download.
MODEL_NAME = 'shard_graph'
# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'
# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join('training', 'object-detection.pbtxt')
NUM_CLASSES = 90
Load a (frozen) Tensorflow model into memory.
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
Loading label map
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)
Helper code
def load_image_into_numpy_array(image):
(im_width, im_height) = image.size
return np.array(image.getdata()).reshape(
(im_height, im_width, 3)).astype(np.uint8)
Detection
# For the sake of simplicity we will use only 2 images:
# image1.jpg
# image2.jpg
# If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.
PATH_TO_TEST_IMAGES_DIR = 'test_images'
TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'frame_{}.png'.format(i)) for i in range(0, 2) ]
# Size, in inches, of the output images.
IMAGE_SIZE = (12, 8)
-
with detection_graph.as_default():
with tf.Session(graph=detection_graph) as sess:
# Definite input and output Tensors for detection_graph
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
# Each box represents a part of the image where a particular object was detected.
detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
# Each score represent how level of confidence for each of the objects.
# Score is shown on the result image, together with the class label.
detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
num_detections = detection_graph.get_tensor_by_name('num_detections:0')
for image_path in TEST_IMAGE_PATHS:
image = Image.open(image_path)
# the array based representation of the image will be used later in order to prepare the
# result image with boxes and labels on it.
image_np = load_image_into_numpy_array(image)
# Expand dimensions since the model expects images to have shape: [1, None, None, 3]
image_np_expanded = np.expand_dims(image_np, axis=0)
# Actual detection.
(boxes, scores, classes, num) = sess.run(
[detection_boxes, detection_scores, detection_classes, num_detections],
feed_dict={image_tensor: image_np_expanded})
# Visualization of the results of a detection.
vis_util.visualize_boxes_and_labels_on_image_array(
image_np,
np.squeeze(boxes),
np.squeeze(classes).astype(np.int32),
np.squeeze(scores),
category_index,
use_normalized_coordinates=True,
line_thickness=8)
plt.figure(figsize=IMAGE_SIZE)
plt.imshow(image_np)
The last part of the script is throwing the Error:
----------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-62-7493eea60222> in <module>()
14 # the array based representation of the image will be used later in order to prepare the
15 # result image with boxes and labels on it.
---> 16 image_np = load_image_into_numpy_array(image)
17 # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
18 image_np_expanded = np.expand_dims(image_np, axis=0)
<ipython-input-60-af094dcdd84a> in load_image_into_numpy_array(image)
2 (im_width, im_height) = image.size
3 return np.array(image.getdata()).reshape(
----> 4 (im_height, im_width, 3)).astype(np.uint8)
ValueError: cannot reshape array of size 344960 into shape (490,704,3)
Edit:
So I changed the last line in this function:
def load_image_into_numpy_array(image):
(im_width, im_height) = image.size
return np.array(image.getdata()).reshape(
(im_height, im_width, 3)).astype(np.uint8)
to:
(im_height, im_width)).astype(np.uint8)
And the ValueError was solved. But now another ValueError connected to the array format is raised:
----------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-107-7493eea60222> in <module>()
20 (boxes, scores, classes, num) = sess.run(
21 [detection_boxes, detection_scores, detection_classes, num_detections],
---> 22 feed_dict={image_tensor: image_np_expanded})
23 # Visualization of the results of a detection.
24 vis_util.visualize_boxes_and_labels_on_image_array(
~/.local/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
898 try:
899 result = self._run(None, fetches, feed_dict, options_ptr,
--> 900 run_metadata_ptr)
901 if run_metadata:
902 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)
~/.local/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
1109 'which has shape %r' %
1110 (np_val.shape, subfeed_t.name,
-> 1111 str(subfeed_t.get_shape())))
1112 if not self.graph.is_feedable(subfeed_t):
1113 raise ValueError('Tensor %s may not be fed.' % subfeed_t)
ValueError: Cannot feed value of shape (1, 490, 704) for Tensor 'image_tensor:0', which has shape '(?, ?, ?, 3)'
Does that mean that this tensorflow-model is not designed for grayscale images? Is there a way to make it work?
SOLUTION
Thanks to Matan Hugi it works just fine now. All I had to do is change this function to:
def load_image_into_numpy_array(image):
# The function supports only grayscale images
last_axis = -1
dim_to_repeat = 2
repeats = 3
grscale_img_3dims = np.expand_dims(image, last_axis)
training_image = np.repeat(grscale_img_3dims, repeats, dim_to_repeat).astype('uint8')
assert len(training_image.shape) == 3
assert training_image.shape[-1] == 3
return training_image
Tensorflow expected input which is formated in NHWC format,
which means: (BATCH, HEIGHT, WIDTH, CHANNELS).
Step 1 - Add last dimension:
last_axis = -1
grscale_img_3dims = np.expand_dims(image, last_axis)
Step 2 - Repeat the last dimension 3 times:
dim_to_repeat = 2
repeats = 3
np.repeat(grscale_img_3dims, repeats, dim_to_repeat)
So your function should be:
def load_image_into_numpy_array(image):
# The function supports only grayscale images
assert len(image.shape) == 2, "Not a grayscale input image"
last_axis = -1
dim_to_repeat = 2
repeats = 3
grscale_img_3dims = np.expand_dims(image, last_axis)
training_image = np.repeat(grscale_img_3dims, repeats, dim_to_repeat).astype('uint8')
assert len(training_image.shape) == 3
assert training_image.shape[-1] == 3
return training_image