Ask Your Question
0

How to determine the image format ?

asked 2014-05-04 04:03:34 -0500

beatrix.kiddo gravatar image

updated 2014-05-04 04:12:04 -0500

berak gravatar image

Hi, i'm currently learning to do image resize with OpenCV java and i notice that i need to imencode to MatOfByte, beofre calling toArray. I tried resize into MatOfByte directly, but calling toArray causes exception.

With imencode, i need to specify the image format, and i want a jpg to be resized into jpg, a png into png, etc. So is there any ways i can detect the image type with opencv, so i can pass the correct format extension to the imencode ?

    Mat image = Highgui.imread("h:/opencv.jpg");
    Mat converted = new Mat();
    Imgproc.resize(image, converted, new Size(1140, 1140), 0, 0, Imgproc.INTER_AREA);
    Highgui.imwrite("h:/opencv_1140.jpg", converted);
    MatOfByte byteMat = new MatOfByte();
    String fileFormat = ...// detect file format from source image, but how ? ex ".jpg"
    Highgui.imencode(fileFormat, converted, byteMat);
    byte[] array = byteMat.toArray();
edit retag flag offensive close merge delete

Comments

1

you can't .

once a image is decoded(from, e.g tiff) it is bgr pixels now, it does not remember, 'where it came from'

berak gravatar imageberak ( 2014-05-04 04:17:51 -0500 )edit

Thanks for clarifying this !

beatrix.kiddo gravatar imagebeatrix.kiddo ( 2014-05-05 04:21:57 -0500 )edit

1 answer

Sort by ยป oldest newest most voted
1

answered 2014-05-04 06:35:22 -0500

AR0x7E7 gravatar image

Note: I don't use Java in combination wit opencv, but it should work like this:

If the procedure you described really is in the same method scope you could simply extract the letters behind the last '.' of the path from the image path you pass to _imread_ - i.e. 'jpg' from "h:\opencv.jpg" - and then pass it on to _imencode_

For this to work you need to save the path of the image loaded, i.e.

String image_in = "h:/opencv.jpg";
Mat image = Highgui.imread(image_in);

Later you use i.e. String.split function

String[] image_in_splits = image_in.split(".");
String fileFormat = image_in_splits[image_in_splits.length - 1];
edit flag offensive delete link more

Comments

Thanks for the idea. And my apology for not being clear in my original post, because the image is actually downloaded from the network, and the filename could be not having an extension. And worse, trying to sniff the type from mime type can also go wrong, since a Content-Type can also be spoofed. I'm currently using a content-type sniffer 3rd party library to 'guess' the image type.

beatrix.kiddo gravatar imagebeatrix.kiddo ( 2014-05-05 04:21:40 -0500 )edit

Question Tools

Stats

Asked: 2014-05-04 04:03:34 -0500

Seen: 5,092 times

Last updated: May 04 '14