-1

Planning on using Tensorflow Lite for image classification.

To test the model, using Fashion-MNIST database to create the model following a Tensorflow basic example from their website. Created and saved the model and want to test it in TF Lite.

I want to save an image from the mentioned database to predict its class in TF Lite. This is the code to check the images (some of them from Google search):

import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import mnist
import tensorflow as tf
import base64
import io
from os.path import dirname, join
from PIL import Image
from matplotlib.pyplot import imread

fashion_mnist = tf.keras.datasets.fashion_mnist
(train_X, train_y), (test_X, test_y) = fashion_mnist.load_data()

# Function to check image format
def check_mnist_image_format(image_array):
    print(f"Image {index} shape: {image_array.shape}")
    print(f"Image {index} data type: {image_array.dtype}")
    print(f"Image {index} min pixel value: {np.min(image_array)}")
    print(f"Image {index} max pixel value: {np.max(image_array)}")

# Check the format of the first training image
check_mnist_image_format(train_X[0], 0)

filename = join(dirname("/home/gachaconr/tf/"), 'image.unit8')
with open(filename, 'wb') as file:
    file.write(train_X[0])
    print("image saved")    

# Open the image file
image_array = imread(filename)
check_mnist_image_format(image_array)

Saving the image with extension .unit8 since that the format of the image database given by the properties given by the function check_mnist_image_format

The image is saved as expected but the function imread cannot read it. This is the error:

Traceback (most recent call last):
File "/home/gachaconr/tf/imagemnistdatacheck.py", line 40, in <module>
     image_array = imread(filename)
                   ^^^^^^^^^^^^^^^^
File "/home/gachaconr/tf/lib/python3.12/site-packages/matplotlib/pyplot.py", line 2607, in imread
     return matplotlib.image.imread(fname, format)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/gachaconr/tf/lib/python3.12/site-packages/matplotlib/image.py", line 1512, in imread
     with img_open(fname) as image:
          ^^^^^^^^^^^^^^^
File "/home/gachaconr/tf/lib/python3.12/site-packages/PIL/Image.py", line 3532, in open
     raise UnidentifiedImageError(msg)
PIL.UnidentifiedImageError: cannot identify image file '/home/gachaconr/tf/image.unit8'

How can I accomplish the mentioned task? What am I doing wrong?

1
  • what is image.unit8 supposed to be? Commented Mar 31 at 18:35

2 Answers 2

-1
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from PIL import Image
from os.path import join, dirname

# Load Fashion-MNIST dataset
fashion_mnist = tf.keras.datasets.fashion_mnist
(train_X, train_y), (test_X, test_y) = fashion_mnist.load_data()

# Function to check image format
def check_mnist_image_format(image_array, index):
    print(f"Image {index} shape: {image_array.shape}")
    print(f"Image {index} data type: {image_array.dtype}")
    print(f"Image {index} min pixel value: {np.min(image_array)}")
    print(f"Image {index} max pixel value: {np.max(image_array)}")

# Check the format of the first training image
check_mnist_image_format(train_X[0], 0)

# Save the image properly as PNG
filename = join(dirname("/home/gachaconr/tf/"), 'image.png')
image = Image.fromarray(train_X[0])  # Convert NumPy array to PIL image
image.save(filename)
print("Image saved successfully as PNG.")

# Reload the image using PIL
loaded_image = Image.open(filename)
loaded_image_array = np.array(loaded_image)

# Check the reloaded image format
check_mnist_image_format(loaded_image_array, "Reloaded Image")
Sign up to request clarification or add additional context in comments.

3 Comments

please review How to Answer.
describe answer outside code.
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
-1

Thanks Somnath.

After some reading this is the code that works:

import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import mnist
#import cv2
# TensorFlow and tf.keras
import tensorflow as tf
import base64
import io
from os.path import dirname, join
#from com.chaquo.python import Python
from PIL import Image
from matplotlib.pyplot import imread

fashion_mnist = tf.keras.datasets.fashion_mnist

# Load MNIST dataset
(train_X, train_y), (test_X, test_y) = fashion_mnist.load_data()

# Function to check image format
def check_mnist_image_format(image_array, index):
    print(f"Image {index} shape: {image_array.shape}")
    print(f"Image {index} data type: {image_array.dtype}")
    print(f"Image {index} min pixel value: {np.min(image_array)}")
    print(f"Image {index} max pixel value: {np.max(image_array)}")

    # Visualize the image
    #plt.imshow(image_array, cmap='gray')
    #plt.title(f"Image {index}")
    #plt.show()

# Check the format of the first training image
check_mnist_image_format(train_X[0], 0)

filename = join(dirname("/home/gachaconr/tf/"), 'imageXX.jpg')
img = train_X[0]
image = Image.fromarray(img.astype(np.uint8))
image.save(filename)
print("image saved")    

# Open the image file
image_array = imread(filename)
# Convert the image to a NumPy array
check_mnist_image_format(image_array, 0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.