1

Could you please suggest a library (or a snippet) to implement pre-processing Python methods (e.g. numpy.expand_dims() or img_to_array) on Android API 18 (to deploy an app based on TensorFlow Mobile)? There are analogous libraries to Python on Java (e.g. ND4J), but they require device or emulator that runs API level 21 or higher.

from keras.preprocessing.image import img_to_array
import numpy as np

    image = img_to_array(image)
    image = np.expand_dims(image, axis=0)
    image /= 255.
A. Gimal
  • 15
  • 4

1 Answers1

0

I an interactive session:

In [168]: np.source(np.expand_dims)
In file: /usr/local/lib/python3.5/dist-packages/numpy/lib/shape_base.py

def expand_dims(a, axis):
    """
    .... docs
    """
    a = asarray(a)
    shape = a.shape
    if axis > a.ndim or axis < -a.ndim - 1:
        # 2017-05-17, 1.13.0
        warnings.warn("Both axis > a.ndim and axis < -a.ndim - 1 are "
                      "deprecated and will raise an AxisError in the future.",
                      DeprecationWarning, stacklevel=2)
    # When the deprecation period expires, delete this if block,
    if axis < 0:
        axis = axis + a.ndim + 1
    # and uncomment the following line.
    # axis = normalize_axis_index(axis, a.ndim + 1)
    return a.reshape(shape[:axis] + (1,) + shape[axis:])

So basically it uses reshape, with a shape that includes a size 1 dimension in the right place. That could also have been done with the [:,:,np.newaxis,...] syntax.

Whether any of that is portable to Java depends on the array implementation in that language.

hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • Thanks a lot for the answer. I saw the source code. My question is exactly related to this: `Whether any of that is portable to Java depends on the array implementation in that language.` I have written null lines in Java before and to port my Python code to Java is the only way for my image preprocessing needs. – A. Gimal Sep 05 '17 at 17:08
  • This kind of reshape is easy in `numpy` because the data is actually stored in a 1d buffer, and the shape (dimensions) is stored as a tuple. Shape affects interpretation and iteration over the data, but doesn't affect storage. But if a multidimensional array is stored as an array of arrays, as with Python lists, reshaping of any kind is a lot more work. – hpaulj Sep 05 '17 at 17:28