Tensorflow numpy image reshape [grayscale images]

2024/10/7 20:36:18

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 zipfilefrom 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_utilfrom 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.sizereturn 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_graphimage_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 the15       # 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.size3   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.sizereturn 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 imageslast_axis = -1dim_to_repeat = 2repeats = 3grscale_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) == 3assert training_image.shape[-1] == 3return training_image
Answer

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 imagesassert len(image.shape) == 2, "Not a grayscale input image" last_axis = -1dim_to_repeat = 2repeats = 3grscale_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) == 3assert training_image.shape[-1] == 3return training_image
https://en.xdnf.cn/q/70206.html

Related Q&A

Merge numpy arrays returned from loop

I have a loop that generates numpy arrays:for x in range(0, 1000):myArray = myFunction(x)The returned array is always one dimensional. I want to combine all the arrays into one array (also one dimensio…

Play mp3 using Python, PyQt, and Phonon

I been trying all day to figure out the Qts Phonon library with Python. My long term goal is to see if I could get it to play a mms:// stream, but since I cant find an implementation of this done anywh…

Python dictionary keys(which are class objects) comparison with multiple comparer

I am using custom objects as keys in python dictionary. These objects has some default hash and eq methods defined which are being used in default comparison But in some function i need to use a diffe…

How can I make np.save work for an ndarray subclass?

I want to be able to save my array subclass to a npy file, and recover the result later.Something like:>>> class MyArray(np.ndarray): pass >>> data = MyArray(np.arange(10)) >>&g…

With ResNet50 the validation accuracy and loss is not changing

I am trying to do image recognition with ResNet50 in Python (keras). I tried to do the same task with VGG16, and I got some results like these (which seem okay to me): resultsVGG16 . The training and v…

string has incorrect type (expected str, got spacy.tokens.doc.Doc)

I have a dataframe:train_review = train[review] train_reviewIt looks like:0 With all this stuff going down at the moment w... 1 \The Classic War of the Worlds\" by Timothy Hi... 2 T…

custom URLs using django rest framework

I am trying to use the django rest framework to expose my models as APIs.serializersclass UserSerializer(serializers.HyperlinkedModelSerializer):class Meta:model = Userviewsetclass UserViewSet(viewsets…

Does python logging.FileHandler use block buffering by default?

The logging handler classes have a flush() method. And looking at the code, logging.FileHandler does not pass a specific buffering mode when calling open(). Therefore when you write to a log file, it …

Non brute force solution to Project Euler problem 25

Project Euler problem 25:The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be F1 = 1, F2 = 1, F3 = 2, F4 = 3, F5 =…

python:class attribute/variable inheritance with polymorphism?

In my endeavours as a python-apprentice i got recently stuck at some odd (from my point of view) behaviour if i tried to work with class attributes. Im not complaining, but would appreciate some helpfu…