Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add JPEG Quality/Compression #11

Open
tom131313 opened this issue Nov 24, 2020 · 0 comments
Open

Add JPEG Quality/Compression #11

tom131313 opened this issue Nov 24, 2020 · 0 comments

Comments

@tom131313
Copy link

@mesutpiskin (moved this issue from the wrong place and corrected it - major change to my thinking)
Thanks for this project. Well done! It's just what I needed for a simple server of a camera frame with an overlay of an OpenCV drawing.

I wanted to control the JPG quality so I gleaned a technique from StackOverflow answers concerning encoding Java Swing types. I had posted that yesterday in the wrong issue but I browsed through your code today and I see you encoded the Mat to JPG twice - once using OpenCV and once using Swing. That duplication is unnecessary and the OpenCV is much easier to add compression so here's my suggestion of removing the Swing JPG encoding and adding Quality to OpenCV JPG encoding. The method name Mat2bufferedImage isn't as precise anymore and should be changed.

Change this in run() pushImage(imag, 10); // example of low quality, high compression

   public void pushImage(Mat frame, int quality) throws IOException {
        if (frame == null)
            return;
        try {
            outputStream = socket.getOutputStream();

            byte[] imageBytes = Mat2bufferedImage(frame, quality);

            outputStream.write(("Content-type: image/jpeg\r\n" +
                    "Content-Length: " + imageBytes.length + "\r\n" +
                    "\r\n").getBytes());

            outputStream.write(imageBytes);

            outputStream.write(("\r\n--" + boundary + "\r\n").getBytes());

        } catch (Exception ex) {
            socket = serverSocket.accept();
            writeHeader(socket.getOutputStream(), boundary);
        }
    }
   
    public static byte[] Mat2bufferedImage(Mat image, int quality) throws IOException {

        // jpg quality; 0 high compression to 100 low compression

        MatOfByte bytemat = new MatOfByte();

        MatOfInt parameters = new MatOfInt(Imgcodecs.IMWRITE_JPEG_QUALITY, quality); // pair-wise; param1, value1, ...

        Imgcodecs.imencode(".jpg", image, bytemat, parameters);

        return bytemat.toArray();
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant