添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I use JavaCV (not OpenCV). My goal is to obtain a Mat object from an image that is stored as a Resource. Then I'm going to pass this Mat into opencv_imgproc.matchTemplate method. I've managed to write this bad code:

    InputStream in = getClass().getResourceAsStream("Lenna32.png");
    BufferedImage image = ImageIO.read(in);
    Frame f = new Java2DFrameConverter().getFrame(image);
    Mat mat = new OpenCVFrameConverter.ToMat().convert(f);

This works in some cases. The problems are:

  • For png images that has transparency channel (that is 32BPP), it shifts channels, so that R=00 G=33 B=66 A=FF turns to R=33 G=66 B=FF

  • On my target environment, I can't use ImageIO

  • There are too many object conversions InputStream -> BufferedImage -> Frame -> Mat. I feel like there should be a simple and effective way to do this.
  • What is the best way to create Mat from a Resource?

    I resolved this by reading bytes from InputStream and passing them into imdecode function:

    InputStream is = context.getResourceAsStream("Lenna32.png");
    int nRead;
    byte[] data = new byte[16 * 1024];
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    while ((nRead = is.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, nRead);
    byte[] bytes = buffer.toByteArray();
    Mat mat = imdecode(new Mat(bytes), CV_LOAD_IMAGE_UNCHANGED);
                    If you can use Apache Commons IO you can convert the input stream directly to a byte array with a one-liner with IOUtils.toByteArray(is);
    – Semaphor
                    Dec 20, 2018 at 14:40
    

    Just for reference, in order to convert InputStream to Mat, @Kotlin:

    val bytes = inputStream.readBytes()
    val mat = Mat(1, bytes.size, CvType.CV_8UC1)
    mat.put(0, 0, bytes)
    return Imgcodecs.imdecode(mat, Imgcodecs.IMREAD_UNCHANGED)
            

    Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.