Converts an INDArray to a Bitmap. Only intended for images with rank 3.

@param array to convert
@param dataType from JavaCV (DEPTH_FLOAT, DEPTH_UBYTE, etc), or -1 to use same type as the INDArray
@return data copied to a Frame
497699
public Bitmap asBitmap(INDArray array, int dataType) {
        return converter2.convert(asFrame(array, dataType));
    }
307429
public static ByteBuffer convertImageData(BufferedImage bi) {
        DataBuffer buff = bi.getRaster().getDataBuffer();
        // ClassCastException thrown if buff not instanceof DataBufferByte because raster data is not necessarily bytes.
        // Convert the original buffered image to grayscale.
        if (!(buff instanceof DataBufferByte)) {
            BufferedImage grayscaleImage = ImageHelper.convertImageToGrayscale(bi);
            buff = grayscaleImage.getRaster().getDataBuffer();
        }
        byte[] pixelData = ((DataBufferByte) buff).getData();
        //        return ByteBuffer.wrap(pixelData);
        ByteBuffer buf = ByteBuffer.allocateDirect(pixelData.length);
        buf.order(ByteOrder.nativeOrder());
        buf.put(pixelData);
        ((Buffer) buf).flip();
        return buf;
    }
247252
public static Basic1DMatrix fromBinary(byte[] array) {
        ByteBuffer buffer = ByteBuffer.wrap(array);

        if (buffer.get() != MATRIX_TAG) {
            throw new IllegalArgumentException("Can not decode Basic1DMatrix from the given byte array.");
        }

        int rows = buffer.getInt();
        int columns = buffer.getInt();
        int capacity = rows * columns;
        double[] values = new double[capacity];

        for (int i = 0; i < capacity; i++) {
            values[i] = buffer.getDouble();
        }

        return new Basic1DMatrix(rows, columns, values);
    }
235634
private BufferedImage to16Bit1ComponentGrayScale(int[][] decoded, int precision, int width, int height) {
        BufferedImage image;
        if (precision == 16) {
            image = new BufferedImage(width, height, BufferedImage.TYPE_USHORT_GRAY);
        }
        else {
            ColorModel colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY), new int[] {precision}, false, false, Transparency.OPAQUE, DataBuffer.TYPE_USHORT);
            image = new BufferedImage(colorModel, colorModel.createCompatibleWritableRaster(width, height), colorModel.isAlphaPremultiplied(), null);
        }

        short[] imageBuffer = ((DataBufferUShort) image.getRaster().getDataBuffer()).getData();

        for (int i = 0; i < imageBuffer.length; i++) {
            imageBuffer[i] = (short) decoded[0][i];
        }

        return image;
    }
400834
public Object convertResult(final Class<?> type) {
		try {
			if (type.isArray()) {
				return TYPE_MAP.get("array").invoke(this);
			}
			if (!TYPE_MAP.containsKey(type)) {
				return getNext(result);
			}
			return TYPE_MAP.get(type).invoke(this);
		} catch (final Exception e) {
			e.printStackTrace();
			return null;
		}
	}
790163
public byte[] drawTileData(short[][] pixelValues) {
		BufferedImage image = drawTile(pixelValues);
		byte[] bytes = getImageBytes(image);
		return bytes;
	}
384211
public final static Object toObjectArray(final Object array) {
        if (!array.getClass().isArray()) {
            return array;
        }
        final Class<?> clazz = PRIMITIVE_TO_OBJ.get(array.getClass().getComponentType());
        return setArray(clazz, array);
    }
1027541
private BufferedImage convertImage(BufferedImage image)
    {
        if (image.getType() == BufferedImage.TYPE_INT_RGB)
        {
            return image;
        }
        else
        {
            BufferedImage newImage = new BufferedImage(image.getWidth(),
                                                       image.getHeight(),
                                                       BufferedImage.TYPE_INT_RGB);
            newImage.getGraphics().drawImage(image, 0, 0, null);
            return newImage;
        }
    }
703824
private BufferedImage renderImageGrayscale(INDArray array) {
        BufferedImage imageToRender = new BufferedImage(array.columns(), array.rows(), BufferedImage.TYPE_BYTE_GRAY);
        for (int x = 0; x < array.columns(); x++) {
            for (int y = 0; y < array.rows(); y++) {
                imageToRender.getRaster().setSample(x, y, 0, (int) (255 * array.getRow(y).getDouble(x)));
            }
        }

        return imageToRender;
    }
901380
@Override
    public INDArray compress(float[] data, int[] shape, char order) {
        FloatPointer pointer = new FloatPointer(data);

        DataBuffer shapeInfo = Nd4j.getShapeInfoProvider().createShapeInformation(ArrayUtil.toLongArray(shape), order, DataType.FLOAT).getFirst();
        DataBuffer buffer = compressPointer(DataTypeEx.FLOAT, pointer, data.length, 4);

        return Nd4j.createArrayFromShapeBuffer(buffer, shapeInfo);
    }
175014
public static byte[] getPixelsBGR(BufferedImage img, int y, int w, byte[] array, int[] temp) {
    final int x = 0;
    final int h = 1;

    assert array.length == temp.length * nrChannels(img);
    assert (temp.length == w);

    int imageType = img.getType();
    Raster raster;
    switch (imageType) {
      case BufferedImage.TYPE_3BYTE_BGR:
      case BufferedImage.TYPE_4BYTE_ABGR:
      case BufferedImage.TYPE_4BYTE_ABGR_PRE:
      case BufferedImage.TYPE_BYTE_GRAY:
        raster = img.getRaster();
        //int ttype= raster.getTransferType();
        raster.getDataElements(x, y, w, h, array);
        break;
      case BufferedImage.TYPE_INT_BGR:
        raster = img.getRaster();
        raster.getDataElements(x, y, w, h, temp);
        ints2bytes(temp, array, 0, 1, 2);  // bgr -->  bgr
        break;
      case BufferedImage.TYPE_INT_RGB:
        raster = img.getRaster();
        raster.getDataElements(x, y, w, h, temp);
        ints2bytes(temp, array, 2, 1, 0);  // rgb -->  bgr
        break;
      case BufferedImage.TYPE_INT_ARGB:
      case BufferedImage.TYPE_INT_ARGB_PRE:
        raster = img.getRaster();
        raster.getDataElements(x, y, w, h, temp);
        ints2bytes(temp, array, 2, 1, 0, 3);  // argb -->  abgr
        break;
      case BufferedImage.TYPE_CUSTOM: // TODO: works for my icon image loader, but else ???
        img.getRGB(x, y, w, h, temp, 0, w);
        ints2bytes(temp, array, 2, 1, 0, 3);  // argb -->  abgr
        break;
      default:
        img.getRGB(x, y, w, h, temp, 0, w);
        ints2bytes(temp, array, 2, 1, 0);  // rgb -->  bgr
        break;
    }

    return array;
  }
467781
@SuppressWarnings("unchecked")
    public BaseBo fromByteArray(byte[] data) {
        Map<String, Object> dataMap = null;
        try {
            dataMap = data != null ? SerializationUtils.fromByteArray(data, Map.class) : null;
        } catch (Exception e) {
            dataMap = null;
        }
        return fromMap(dataMap);
    }
523529
private BufferedImage to24Bit3ComponentRGB(int[][] decoded, int width, int height) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        byte[] imageBuffer = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();

        for (int i = 0; i < imageBuffer.length / 3; i++) {
            // Convert to RGB (BGR)
            imageBuffer[i * 3 + 2] = (byte) decoded[0][i];
            imageBuffer[i * 3 + 1] = (byte) decoded[1][i];
            imageBuffer[i * 3] = (byte) decoded[2][i];
        }

        return image;
    }
1352485
public static Bitmap decodeSampledBitmapFromByteArray(byte[] picture,
                                                          int reqWidth, int reqHeight) {

        // First decode with inJustDecodeBounds=true to check dimensions
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(picture, 0, picture.length, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeByteArray(picture, 0, picture.length, options);
    }
1104362
public TF_Tensor tensorFromNDArray(INDArray ndArray) {
       if(ndArray == null) {
           throw new IllegalArgumentException("NDArray must not be null!");
       }
        //we infer data type from the ndarray.databuffer()
        //for now we throw an exception
        if(ndArray.data() == null) {
           throw new IllegalArgumentException("Unable to infer data type from null databuffer");
       }

        if(ndArray.isView() || ndArray.ordering() != 'c') {
            ndArray = ndArray.dup('c');
        }


        long[] ndShape = ndArray.shape();
        long[] tfShape = new long[ndShape.length];
        System.arraycopy(ndShape, 0, tfShape, 0, ndShape.length);

        int type;
        DataBuffer data = ndArray.data();
        DataType dataType = data.dataType();
        switch (dataType) {
            case DOUBLE: type = DT_DOUBLE; break;
            case FLOAT:  type = DT_FLOAT;  break;
            case INT:    type = DT_INT32;  break;
            case HALF:   type = DT_HALF;   break;
            case COMPRESSED:
                CompressedDataBuffer compressedData = (CompressedDataBuffer)data;
                CompressionDescriptor desc = compressedData.getCompressionDescriptor();
                String algo = desc.getCompressionAlgorithm();
                switch (algo) {
                    case "FLOAT16": type = DT_HALF;   break;
                    case "INT8":    type = DT_INT8;   break;
                    case "UINT8":   type = DT_UINT8;  break;
                    case "INT16":   type = DT_INT16;  break;
                    case "UINT16":  type = DT_UINT16; break;
                    default: throw new IllegalArgumentException("Unsupported compression algorithm: " + algo);
                }
                break;
            case LONG: type = DT_INT64; break;
            case UTF8: type = DT_STRING; break;
            default: throw new IllegalArgumentException("Unsupported data type: " + dataType);
        }

        try {
            Nd4j.getAffinityManager().ensureLocation(ndArray, AffinityManager.Location.HOST);
        } catch (Exception e) {
            // ND4J won't let us access compressed data in GPU memory, so we'll leave TensorFlow do the conversion instead
            ndArray.getDouble(0); // forces decompression and data copy to host
            data = ndArray.data();
            dataType = data.dataType();
            switch (dataType) {
                case DOUBLE: type = DT_DOUBLE; break;
                case FLOAT:  type = DT_FLOAT;  break;
                case INT:    type = DT_INT32;  break;
                case LONG:   type = DT_INT64;  break;
                case UTF8: type = DT_STRING; break;
                default: throw new IllegalArgumentException("Unsupported data type: " + dataType);
            }
        }


        LongPointer longPointer = new LongPointer(tfShape);
        TF_Tensor tf_tensor = null;

        if (type == DT_STRING) {
            long size = 0;
            long length = ndArray.length();
            BytePointer[] strings = new BytePointer[(int)length];
            for (int i = 0; i < length; i++) {
                strings[i] = new BytePointer(ndArray.getString(i));
                size += TF_StringEncodedSize(strings[i].capacity());
            }
            tf_tensor = TF_AllocateTensor(
                    type,
                    longPointer,
                    tfShape.length,
                    8 * length + size);

            long offset = 0;
            BytePointer tf_data = new BytePointer(TF_TensorData(tf_tensor)).capacity(TF_TensorByteSize(tf_tensor));
            TF_Status status = TF_NewStatus();
            for (int i = 0; i < length; i++) {
                tf_data.position(8 * i).putLong(offset);
                offset += TF_StringEncode(strings[i], strings[i].capacity() - 1, tf_data.position(8 * length + offset), tf_data.capacity() - tf_data.position(), status);
                if (TF_GetCode(status) != TF_OK) {
                    throw new IllegalStateException("ERROR: Unable to convert tensor " + TF_Message(status).getString());
                }
            }
            TF_DeleteStatus(status);
        } else {
            tf_tensor = TF_NewTensor(
                    type,
                    longPointer,
                    tfShape.length,
                    data.pointer(),
                    data.length() * data.getElementSize(),
                    calling,null);
        }

        return tf_tensor;

    }
993374
public static ByteArrayInputStream toPNGInputStream(Bitmap bitmap) {
		ByteArrayOutputStream bytes = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);
		return new ByteArrayInputStream(bytes.toByteArray());
	}
1337010
public static byte[] bufferedImageToBMPByteArray(BufferedImage image, BufferedImage bufferedImage) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            /* ImageTypeSpecifier type =
             ImageTypeSpecifier.createFromRenderedImage(image);
             Iterator<ImageWriter> iter = ImageIO.getImageWriters(type, "bmp");
             System.err.println(ImageIO.getWriterFormatNames());
             boolean sig=iter.hasNext();*/
            //BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
            Graphics2D ngraphics = (Graphics2D) bufferedImage.getGraphics();
            /*ngraphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
             RenderingHints.VALUE_INTERPOLATION_BILINEAR);*/
            //ngraphics.drawImage(image, 0, 0,512,384,0,0,image.getWidth(),image.getHeight(), null);        	
            //ngraphics.drawImage(image.getScaledInstance(200, 300, BufferedImage.SCALE_FAST), 0, 0,null);        	
            ngraphics.drawImage(image, 0, 0, null);
            ImageIO.write(bufferedImage, "bmp", baos);
            baos.flush();
            byte[] imageInByte = baos.toByteArray();
            baos.close();
            return imageInByte;
        } catch (IOException ex) {
            Logger.getLogger(PHATImageUtils.class.getName()).log(Level.SEVERE, "bufferedImageToByteArray", ex);
        }
        return null;
    }