org.bytedeco.javacpp.BytePointer Java Examples

The following examples show how to use org.bytedeco.javacpp.BytePointer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestPythonExecutioner.java    From deeplearning4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testByteBufferInput() throws Exception{
    //ByteBuffer buff = ByteBuffer.allocateDirect(3);
    INDArray buff = Nd4j.zeros(new int[]{3}, DataType.BYTE);
    buff.putScalar(0, 97); // a
    buff.putScalar(1, 98); // b
    buff.putScalar(2, 99); // c
    ((BaseDataBuffer)buff.data()).syncToPrimary();
    PythonVariables pyInputs = new PythonVariables();
    pyInputs.addBytes("buff", new BytePointer(buff.data().pointer()));

    PythonVariables pyOutputs= new PythonVariables();
    pyOutputs.addStr("out");

    String code = "out = bytes(buff).decode()";
    Python.exec(code, pyInputs, pyOutputs);
    Assert.assertEquals("abc", pyOutputs.getStrValue("out"));

  }
 
Example #2
Source File: Int8.java    From nd4j with Apache License 2.0 6 votes vote down vote up
@Override
protected CompressedDataBuffer compressPointer(DataBuffer.TypeEx srcType, Pointer srcPointer, int length,
                int elementSize) {

    BytePointer ptr = new BytePointer(length);
    CompressionDescriptor descriptor = new CompressionDescriptor();
    descriptor.setCompressedLength(length * 1);
    descriptor.setOriginalLength(length * elementSize);
    descriptor.setOriginalElementSize(elementSize);
    descriptor.setNumberOfElements(length);

    descriptor.setCompressionAlgorithm(getDescriptor());
    descriptor.setCompressionType(getCompressionType());

    CompressedDataBuffer buffer = new CompressedDataBuffer(ptr, descriptor);

    Nd4j.getNDArrayFactory().convertDataEx(srcType, srcPointer, DataBuffer.TypeEx.INT8, ptr, length);

    return buffer;
}
 
Example #3
Source File: Int16.java    From nd4j with Apache License 2.0 6 votes vote down vote up
@Override
protected CompressedDataBuffer compressPointer(DataBuffer.TypeEx srcType, Pointer srcPointer, int length,
                int elementSize) {

    BytePointer ptr = new BytePointer(length * 2);
    CompressionDescriptor descriptor = new CompressionDescriptor();
    descriptor.setCompressedLength(length * 2);
    descriptor.setOriginalLength(length * elementSize);
    descriptor.setOriginalElementSize(elementSize);
    descriptor.setNumberOfElements(length);

    descriptor.setCompressionAlgorithm(getDescriptor());
    descriptor.setCompressionType(getCompressionType());

    CompressedDataBuffer buffer = new CompressedDataBuffer(ptr, descriptor);

    Nd4j.getNDArrayFactory().convertDataEx(srcType, srcPointer, DataBuffer.TypeEx.INT16, ptr, length);

    return buffer;
}
 
Example #4
Source File: Session.java    From java with Apache License 2.0 6 votes vote down vote up
private static TF_Session allocate(TF_Graph graphHandle, String target, ConfigProto config) {
  if (graphHandle == null || graphHandle.isNull()) {
    throw new IllegalStateException("Graph has been close()d");
  }
  try (PointerScope scope = new PointerScope()) {
    TF_Status status = TF_Status.newStatus();
    TF_SessionOptions opts = TF_SessionOptions.newSessionOptions();
    if (config != null) {
      BytePointer configBytes = new BytePointer(config.toByteArray());
      TF_SetConfig(opts, configBytes, configBytes.capacity(), status);
      status.throwExceptionIfNotOK();
    }

    TF_Session session = TF_NewSession(graphHandle, opts, status);
    status.throwExceptionIfNotOK();

    return session;
  }
}
 
Example #5
Source File: Gzip.java    From nd4j with Apache License 2.0 6 votes vote down vote up
@Override
public DataBuffer compress(DataBuffer buffer) {
    try {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(stream);
        DataOutputStream dos = new DataOutputStream(gzip);

        buffer.write(dos);
        dos.flush();
        dos.close();

        byte[] bytes = stream.toByteArray();
        //            logger.info("Bytes: {}", Arrays.toString(bytes));
        BytePointer pointer = new BytePointer(bytes);
        CompressionDescriptor descriptor = new CompressionDescriptor(buffer, this);
        descriptor.setCompressedLength(bytes.length);

        CompressedDataBuffer result = new CompressedDataBuffer(pointer, descriptor);

        return result;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #6
Source File: Encoder.java    From JavaAV with GNU General Public License v2.0 6 votes vote down vote up
private void createVideoBuffer() throws JavaAVException {
	picture = new AVPicture();

	if (avpicture_alloc(picture, avContext.pix_fmt(), avContext.width(), avContext.height()) < 0)
		throw new JavaAVException("Could not allocate decoding picture.");

	// like in ffmpeg.c
	videoBufferSize = Math.max(256 * 1024, 8 * avContext.width() * avContext.height());
	videoBuffer = new BytePointer(av_malloc(videoBufferSize));

	int size = avpicture_get_size(avContext.pix_fmt(), avContext.width(), avContext.height());
	if ((pictureBuffer = new BytePointer(av_malloc(size))).isNull()) {
		close();
		throw new JavaAVException("Could not allocate picture buffer.");
	}
}
 
Example #7
Source File: EagerSession.java    From java with Apache License 2.0 6 votes vote down vote up
private static TFE_Context allocate(boolean async, int devicePlacementPolicy, ConfigProto config) {
  try (PointerScope scope = new PointerScope()) {
    TFE_ContextOptions opts = TFE_ContextOptions.newContextOptions();
    TF_Status status = TF_Status.newStatus();
    if (config != null) {
      BytePointer configBytes = new BytePointer(config.toByteArray());
      TFE_ContextOptionsSetConfig(opts, configBytes, configBytes.capacity(), status);
      status.throwExceptionIfNotOK();
    }
    TFE_ContextOptionsSetAsync(opts, (byte)(async ? 1 : 0));
    TFE_ContextOptionsSetDevicePlacementPolicy(opts, devicePlacementPolicy);
    TFE_Context context = TFE_NewContext(opts, status);
    status.throwExceptionIfNotOK();
    return context;
  }
}
 
Example #8
Source File: TestPythonExecutioner.java    From deeplearning4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testByteBufferInplace() throws Exception{
    INDArray buff = Nd4j.zeros(new int[]{3}, DataType.BYTE);
    buff.putScalar(0, 97); // a
    buff.putScalar(1, 98); // b
    buff.putScalar(2, 99); // c
    ((BaseDataBuffer)buff.data()).syncToPrimary();

    PythonVariables pyInputs = new PythonVariables();
    pyInputs.addBytes("buff", new BytePointer(buff.data().pointer()));
    String code = "buff[0]+=2\nbuff[2]-=2";
    Python.exec(code, pyInputs, null);
    Assert.assertEquals("cba", pyInputs.getBytesValue("buff").getString());
    INDArray expected = buff.dup();
    expected.putScalar(0, 99);
    expected.putScalar(2, 97);
    Assert.assertEquals(buff, expected);

}
 
Example #9
Source File: Float16.java    From nd4j with Apache License 2.0 6 votes vote down vote up
@Override
protected CompressedDataBuffer compressPointer(DataBuffer.TypeEx srcType, Pointer srcPointer, int length,
                int elementSize) {

    BytePointer ptr = new BytePointer(length * 2);
    CompressionDescriptor descriptor = new CompressionDescriptor();
    descriptor.setCompressedLength(length * 2);
    descriptor.setOriginalLength(length * elementSize);
    descriptor.setOriginalElementSize(elementSize);
    descriptor.setNumberOfElements(length);

    descriptor.setCompressionAlgorithm(getDescriptor());
    descriptor.setCompressionType(getCompressionType());

    CompressedDataBuffer buffer = new CompressedDataBuffer(ptr, descriptor);

    Nd4j.getNDArrayFactory().convertDataEx(srcType, srcPointer, DataBuffer.TypeEx.FLOAT16, ptr, length);

    return buffer;
}
 
Example #10
Source File: TesseractPlatformExample.java    From tutorials with MIT License 6 votes vote down vote up
@SuppressWarnings("resource")
public static void main(String[] args) {
    try {
        TessBaseAPI tessApi = new TessBaseAPI();
        tessApi.Init("src/main/resources/tessdata", "eng", 3);
        tessApi.SetPageSegMode(1);
        PIX image = org.bytedeco.leptonica.global.lept.pixRead("src/main/resources/images/baeldung.png");
        tessApi.SetImage(image);

        BytePointer outText = tessApi.GetUTF8Text();
        System.out.println(outText.getString());
        tessApi.End();
    } catch(Exception e) {
       e.printStackTrace();
    }
}
 
Example #11
Source File: Gzip.java    From deeplearning4j with Apache License 2.0 6 votes vote down vote up
@Override
public DataBuffer decompress(DataBuffer buffer, DataType dataType) {
    try {

        CompressedDataBuffer compressed = (CompressedDataBuffer) buffer;
        CompressionDescriptor descriptor = compressed.getCompressionDescriptor();

        BytePointer pointer = (BytePointer) compressed.addressPointer();
        ByteArrayInputStream bis = new ByteArrayInputStream(pointer.getStringBytes());
        GZIPInputStream gzip = new GZIPInputStream(bis);
        DataInputStream dis = new DataInputStream(gzip);

        DataBuffer bufferRestored = Nd4j.createBuffer(dataType, descriptor.getNumberOfElements(), false);
        BaseDataBuffer.readHeader(dis);
        bufferRestored.read(dis, DataBuffer.AllocationMode.MIXED_DATA_TYPES, descriptor.getNumberOfElements(), dataType);

        return bufferRestored;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #12
Source File: VertxBufferNumpyInputAdapter.java    From konduit-serving with Apache License 2.0 6 votes vote down vote up
/**
 * Convert Buffer input to NDArray writable. Note that contextData is unused in this implementation of InputAdapter.
 */
@Override
public NDArrayWritable convert(Buffer input, ConverterArgs parameters, Map<String, Object> contextData) {
    Preconditions.checkState(input.length() > 0, "Buffer appears to be empty!");
    INDArray fromNpyPointer = Nd4j.getNDArrayFactory().createFromNpyPointer(
            new BytePointer(input.getByteBuf().nioBuffer())
    );
    if (permuteRequired(parameters)) {
        fromNpyPointer = ImagePermuter.permuteOrder(
                fromNpyPointer,
                parameters.getImageProcessingInitialLayout(),
                parameters.getImageProcessingRequiredLayout()
        );
    }

    return new NDArrayWritable(fromNpyPointer);
}
 
Example #13
Source File: JCublasNDArray.java    From deeplearning4j with Apache License 2.0 6 votes vote down vote up
protected int stringBuffer(FlatBufferBuilder builder, DataBuffer buffer) {
    Preconditions.checkArgument(buffer.dataType() == DataType.UTF8, "This method can be called on UTF8 buffers only");
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(bos);

        val numWords = this.length();
        val ub = (CudaUtf8Buffer) buffer;
        // writing length first
        val t = length();
        val ptr = (BytePointer) ub.pointer();

        // now write all strings as bytes
        for (int i = 0; i < ub.length(); i++) {
            dos.writeByte(ptr.get(i));
        }

        val bytes = bos.toByteArray();
        return FlatArray.createBufferVector(builder, bytes);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #14
Source File: AudioFrame.java    From JavaAV with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a new {@code AudioFrame} with descriptive format and allocates memory
 * for the specified amount of samples.
 *
 * @param format  the format of the samples.
 * @param samples the amount of samples.
 */
public AudioFrame(AudioFormat format, int samples) {
	int channels = format.getChannels();
	int sampleFormat = format.getSampleFormat().value();
	int planes = av_sample_fmt_is_planar(sampleFormat) != 0 ? channels : 1;
	int planeLength = (samples * channels * av_get_bytes_per_sample(sampleFormat)) / planes;

	this.format = format;
	this.samples = samples;
	this.planePointers = new BytePointer[planes];
	this.samplePointer = new PointerPointer(planes);

	for (int i = 0; i < planes; i++) {
		this.planePointers[i] = new BytePointer(av_malloc(planeLength)).capacity(planeLength);
		this.planePointers[i].limit(planeLength);
		this.samplePointer.put(i, planePointers[i]);
	}
}
 
Example #15
Source File: FFmpegVideoImageGrabber.java    From easyCV with Apache License 2.0 6 votes vote down vote up
@Override
protected ByteBuffer saveFrame(AVFrame pFrame, int width, int height) {
	BytePointer data = pFrame.data(0);
	int size = width * height * 3;
	ByteBuffer buf = data.position(0).limit(size).asBuffer();
	if(viwer==null) {
		viwer=new ImageViewer(width,height, BufferedImage.TYPE_3BYTE_BGR);
	}else {
		if(index==0) {
			index++;
			viwer.setSize(width, height);
		}
	}
	
	viwer.show(buf,width,height);
	return buf;
}
 
Example #16
Source File: Audio.java    From JavaAV with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get byte array with interleaved signed {@code byte} samples. Since each sample fits in
 * one byte the possible sample values are within the interval [-2^7, 2^7-1]. It is assumed
 * that the samples within the {@code AudioFrame} are normalized, meaning in [-1, 1].
 *
 * @param frame {@code AudioFrame} with audio samples.
 *
 * @return interleaved byte array with signed samples within [-2^7, 2^7-1].
 */
public static byte[] getAudio8(AudioFrame frame) {
	BytePointer[] planes = frame.getPlanes();
	SampleFormat format = frame.getAudioFormat().getSampleFormat();
	int depth = getFormatDepth(format);

	int length = planes[0].limit() / depth;
	int channels = planes.length;
	byte[] samples = new byte[channels * length];

	for (int i = 0; i < channels; i++) {
		ByteBuffer buffer = planes[i].asByteBuffer();
		int offset = i * channels;

		for (int j = 0, k = offset; j < length; j++) {
			long sample = quantize8(getValue(buffer, format, j * depth).doubleValue() * twoPower7);
			samples[k++] = (byte) (sample & 0x80);

			// interleave
			k += 2 * (channels - 1);
		}
	}

	return samples;
}
 
Example #17
Source File: FrameExperienceMemory.java    From burlap_caffe with Apache License 2.0 6 votes vote down vote up
public FrameExperienceMemory(int size, int maxHistoryLength, PreProcessor preProcessor, ActionSet actionSet, boolean alwaysIncludeMostRecent) {
    if(size < 1){
        throw new RuntimeException("FixedSizeMemory requires memory size > 0; was request size of " + size);
    }
    this.alwaysIncludeMostRecent = alwaysIncludeMostRecent;
    this.experiences = new FrameExperience[size];

    this.currentFrameHistory = new FrameHistory(0, 0);
    this.maxHistoryLength = maxHistoryLength;

    this.preProcessor = preProcessor;
    this.actionSet = actionSet;

    long outputSize = preProcessor.outputSize();

    // Create the frame history data size to be totalHistorySize + a padding on both sides of n - 1
    long paddingSize = (this.maxHistoryLength - 1) * outputSize;
    frameMemory = (new BytePointer(size * outputSize + 2 * paddingSize)).zero();
}
 
Example #18
Source File: NoOp.java    From deeplearning4j with Apache License 2.0 6 votes vote down vote up
@Override
protected CompressedDataBuffer compressPointer(DataTypeEx srcType, Pointer srcPointer, int length,
                                               int elementSize) {

    CompressionDescriptor descriptor = new CompressionDescriptor();
    descriptor.setCompressionType(getCompressionType());
    descriptor.setOriginalLength(length * elementSize);
    descriptor.setCompressionAlgorithm(getDescriptor());
    descriptor.setOriginalElementSize(elementSize);
    descriptor.setCompressedLength(length * elementSize);
    descriptor.setNumberOfElements(length);

    BytePointer ptr = new BytePointer(length * elementSize);

    val perfD = PerformanceTracker.getInstance().helperStartTransaction();

    // this Pointer.memcpy is used intentionally. This method operates on host memory ALWAYS
    Pointer.memcpy(ptr, srcPointer, length * elementSize);

    PerformanceTracker.getInstance().helperRegisterTransaction(0, perfD, length * elementSize, MemcpyDirection.HOST_TO_HOST);

    CompressedDataBuffer buffer = new CompressedDataBuffer(ptr, descriptor);

    return buffer;
}
 
Example #19
Source File: Utf8Buffer.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
public Utf8Buffer(byte[] data, long numWords) {
    super(data.length, false);

    val bp = (BytePointer) pointer;
    bp.put(data);
    this.numWords = numWords;
}
 
Example #20
Source File: OcrService.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
private static String extractAllText(TessBaseAPI api) throws Exception {
    final BytePointer outText;
    final String result;
    outText = api.GetUTF8Text();
    if (outText == null) {
        throw new Exception(TESSERACT_PARSE_ERROR);
    }
    result = outText.getString();
    outText.deallocate();
    return result;
}
 
Example #21
Source File: Utf8Buffer.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
public Utf8Buffer(@NonNull Collection<String> strings) {
    super(Utf8Buffer.stringBufferRequiredLength(strings), false);

    // at this point we should have fully allocated buffer, time to fill length
    val headerLength = (strings.size() + 1) * 8;
    val headerPointer = new LongPointer(this.pointer);
    val dataPointer = new BytePointer(this.pointer);

    numWords = strings.size();

    long cnt = 0;
    long currentLength = 0;
    for (val s: strings) {
        headerPointer.put(cnt++, currentLength);
        val length = s.length();
        val chars = s.toCharArray();

        // putting down chars
        for (int e = 0; e < length; e++) {
            val b = (byte) chars[e];
            val idx = headerLength + currentLength + e;
            dataPointer.put(idx, b);
        }

        currentLength += length;
    }
    headerPointer.put(cnt, currentLength);
}
 
Example #22
Source File: ALEPreProcessor.java    From burlap_caffe with Apache License 2.0 5 votes vote down vote up
@Override
public void convertScreenToData(Mat screen, BytePointer data) {

    Mat gray = new Mat(screen.rows(), screen.cols(), CV_8UC1);
    cvtColor(screen, gray, COLOR_BGR2GRAY);

    Mat downsample = new Mat(scaleHeight, scaleWidth, CV_8UC1, data);
    resize(gray, downsample, new Size(scaleWidth, scaleHeight));
}
 
Example #23
Source File: BrowserTest.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
public String ocr(BufferedImage imgBuff) {
  String parsedOut = null;

  try {
    // Color image to pure black and white
    for (int x = 0; x < imgBuff.getWidth(); x++) {
      for (int y = 0; y < imgBuff.getHeight(); y++) {
        Color color = new Color(imgBuff.getRGB(x, y));
        int red = color.getRed();
        int green = color.getBlue();
        int blue = color.getGreen();
        if (red + green + blue > OCR_COLOR_THRESHOLD) {
          red = green = blue = 0; // Black
        } else {
          red = green = blue = 255; // White
        }
        Color col = new Color(red, green, blue);
        imgBuff.setRGB(x, y, col.getRGB());
      }
    }

    // OCR recognition
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(imgBuff, "png", baos);
    byte[] imageBytes = baos.toByteArray();

    TessBaseAPI api = new TessBaseAPI();
    api.Init(null, "eng");
    ByteBuffer imgBB = ByteBuffer.wrap(imageBytes);

    PIX image = pixReadMem(imgBB, imageBytes.length);
    api.SetImage(image);

    // Get OCR result
    BytePointer outText = api.GetUTF8Text();

    // Destroy used object and release memory
    api.End();
    api.close();
    outText.deallocate();
    pixDestroy(image);

    // OCR corrections
    parsedOut = outText.getString().replaceAll("l", "1").replaceAll("Z", "2").replaceAll("O", "0")
        .replaceAll("B", "8").replaceAll("G", "6").replaceAll("S", "8").replaceAll("'", "")
        .replaceAll("‘", "").replaceAll("\\.", ":").replaceAll("E", "8").replaceAll("o", "0")
        .replaceAll("fl", "0").replaceAll("fi", "6").replaceAll("§", "5").replaceAll("I", "1")
        .replaceAll("T", "7").replaceAll("’", "").replaceAll("U", "0").replaceAll("D", "0");
    if (parsedOut.length() > 7) {
      parsedOut = parsedOut.substring(0, 7) + ":" + parsedOut.substring(8, parsedOut.length());
    }
    parsedOut = parsedOut.replaceAll("::", ":");

    // Remove last part (number of frames)
    int iSpace = parsedOut.lastIndexOf(" ");
    if (iSpace != -1) {
      parsedOut = parsedOut.substring(0, iSpace);
    }
  } catch (IOException e) {
    log.warn("IOException in OCR", e);
  }
  return parsedOut;
}
 
Example #24
Source File: CompressedDataBuffer.java    From nd4j with Apache License 2.0 5 votes vote down vote up
/**
 * Drop-in replacement wrapper for BaseDataBuffer.read() method, aware of CompressedDataBuffer
 * @param s
 * @return
 */
public static DataBuffer readUnknown(DataInputStream s, long length) {
    DataBuffer buffer = Nd4j.createBuffer(length);
    buffer.read(s);
    // if buffer is uncompressed, it'll be valid buffer, so we'll just return it
    if (buffer.dataType() != Type.COMPRESSED)
        return buffer;
    else {
        try {

            // if buffer is compressed one, we''ll restore it here
            String compressionAlgorithm = s.readUTF();
            long compressedLength = s.readLong();
            long originalLength = s.readLong();
            long numberOfElements = s.readLong();

            byte[] temp = new byte[(int) compressedLength];
            for (int i = 0; i < compressedLength; i++) {
                temp[i] = s.readByte();
            }

            Pointer pointer = new BytePointer(temp);
            CompressionDescriptor descriptor = new CompressionDescriptor();
            descriptor.setCompressedLength(compressedLength);
            descriptor.setCompressionAlgorithm(compressionAlgorithm);
            descriptor.setOriginalLength(originalLength);
            descriptor.setNumberOfElements(numberOfElements);
            return new CompressedDataBuffer(pointer, descriptor);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example #25
Source File: CudaUtf8Buffer.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
public CudaUtf8Buffer(byte[] data, long numWords) {
    super(data.length, 1, false);

    lazyAllocateHostPointer();

    val bp = (BytePointer) pointer;
    bp.put(data);
    this.numWords = numWords;
}
 
Example #26
Source File: ImagePlusMatConverter.java    From IJ-OpenCV with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Duplicates {@link ColorProcessor} to the corresponding OpenCV image of
 * type {@link Mat}.
 *
 * @param cp The {@link ColorProcessor} to be converted
 * @return The OpenCV image (of type {@link Mat})
 */
public static Mat toMat(ColorProcessor cp) {
    final int w = cp.getWidth();
    final int h = cp.getHeight();
    final int[] pixels = (int[]) cp.getPixels();
    byte[] bData = new byte[w * h * 3];

    // convert int-encoded RGB values to byte array
    for (int i = 0; i < pixels.length; i++) {
        bData[i * 3 + 0] = (byte) ((pixels[i] >> 16) & 0xFF);	// red
        bData[i * 3 + 1] = (byte) ((pixels[i] >> 8) & 0xFF);	// grn
        bData[i * 3 + 2] = (byte) ((pixels[i]) & 0xFF);	// blu
    }
    return new Mat(h, w, opencv_core.CV_8UC3, new BytePointer(bData));
}
 
Example #27
Source File: ImagePlusMatConverter.java    From IJ-OpenCV with GNU General Public License v3.0 5 votes vote down vote up
/**
     * Duplicates {@link ByteProcessor} to the corresponding OpenCV image of
     * type {@link Mat}.
     *
     * @param bp The {@link ByteProcessor} to be converted
     * @return The OpenCV image (of type {@link Mat})
     */
    public static Mat toMat(ByteProcessor bp) {
        final int w = bp.getWidth();
        final int h = bp.getHeight();
        final byte[] pixels = (byte[]) bp.getPixels();

        // version A - copies the pixel data to a new array
//		Size size = new Size(w, h);
//		Mat mat = new Mat(size, opencv_core.CV_8UC1);
//		mat.data().put(bData);
        // version 2 - reuses the existing pixel array
        return new Mat(h, w, opencv_core.CV_8UC1, new BytePointer(pixels));
    }
 
Example #28
Source File: Hdf5Archive.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
/**
 * Read JSON-formatted string attribute.
 *
 * @param attribute HDF5 attribute to read as JSON formatted string.
 * @return JSON formatted string from HDF5 attribute
 * @throws UnsupportedKerasConfigurationException Unsupported Keras config
 */
private String readAttributeAsJson(Attribute attribute) throws UnsupportedKerasConfigurationException {
    synchronized (Hdf5Archive.LOCK_OBJECT) {
        VarLenType vl = attribute.getVarLenType();
        int currBufferLength = 2048;
        String s;
        /* TODO: find a less hacky way to do this.
         * Reading variable length strings (from attributes) is a giant
         * pain. There does not appear to be any way to determine the
         * length of the string in advance, so we use a hack: choose a
         * buffer size and read the config. If Jackson fails to parse
         * it, then we must not have read the entire config. Increase
         * buffer and repeat.
         */
        while (true) {
            byte[] attrBuffer = new byte[currBufferLength];
            BytePointer attrPointer = new BytePointer(currBufferLength);
            attribute.read(vl, attrPointer);
            attrPointer.get(attrBuffer);
            s = new String(attrBuffer);
            ObjectMapper mapper = new ObjectMapper();
            mapper.enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY);
            try {
                mapper.readTree(s);
                break;
            } catch (IOException e) {
                //OK - we don't know how long the buffer needs to be, so we'll try again with larger buffer
            }

            if(currBufferLength == MAX_BUFFER_SIZE_BYTES){
                throw new UnsupportedKerasConfigurationException("Could not read abnormally long HDF5 attribute: size exceeds " + currBufferLength + " bytes");
            } else {
                currBufferLength = (int)Math.min(MAX_BUFFER_SIZE_BYTES, currBufferLength * 4L);
            }
        }
        vl.deallocate();
        return s;
    }
}
 
Example #29
Source File: CharsSegment.java    From vlpr4j with Apache License 2.0 5 votes vote down vote up
/**
     * 去除车牌上方的钮钉
     * <p>
     * 计算每行元素的阶跃数,如果小于X认为是柳丁,将此行全部填0(涂黑), X可根据实际调整
     * 
     * @param img
     * @return
     */
    private Mat clearLiuDing(Mat img) {
        final int x = this.liuDingSize;
       
        Mat jump = Mat.zeros(1, img.rows(), CV_32F).asMat();
    	CoreFunc.showImage("test", jump);
      
        System.err.println("图像总行数:"+img.rows());
        for (int i = 0; i < img.rows(); i++) {
            int jumpCount = 0;
            for (int j = 0; j < img.cols() - 1; j++) {
                if (img.ptr(i, j).get() != img.ptr(i, j + 1).get())
                    jumpCount++;
            }
            System.err.println("总数:"+jumpCount);
            System.err.println("第"+i+"行");
            byte[] bt=Convert.getBytes((float) jumpCount);
            System.err.println("test:"+bt.length);
            //指定矩阵行的指针
            BytePointer bp= jump.ptr(i);
//            CoreFunc.showImage("test", jump);
//            
            bp.put(bt);
            System.err.println("test:end");
        }
       
        for (int i = 0; i < img.rows(); i++) {
            if (Convert.toFloat(jump.ptr(i)) <= x) {
                for (int j = 0; j < img.cols(); j++) {
                    img.ptr(i, j).put((byte) 0);
                }
            }
        }
        return img;
    }
 
Example #30
Source File: TestFrameExperienceMemory.java    From burlap_caffe with Apache License 2.0 5 votes vote down vote up
@Override
public void convertScreenToData(opencv_core.Mat screen, BytePointer data) {
    if (screen.data().address() == data.address()) {
        return;
    }

    BytePointer screenData = screen.data();
    data.limit(data.position() + frameSize).put(screen.data().limit(frameSize));
}