Using OpenCV Java Bindings to read an image

birdy picture birdy · Mar 30, 2013 · Viewed 22.9k times · Source

I'm using the new OpenCV Java bindings to read an image and do some processing on the image. I'm trying to convert C code to Java using the Java bindings but can't seem to find the relevant methods:

C code:

cv::Mat img = cv::imread(argv[1]);
cv::Mat gray;
cv::cvtColor(img, gray, CV_BGR2GRAY);
int erosion_size = 5;
cv::Mat element = cv::getStructuringElement(cv::MORPH_CROSS,
                                       cv::Size(2 * erosion_size + 1, 2 * erosion_size + 1),
                                       cv::Point(erosion_size, erosion_size) );
cv::erode(gray, gray, element);

I can't find:

  • imread
  • cvtcolor
  • getStructuringElement
  • erode

I looked around the api here: http://docs.opencv.org/java/

Unfortunately the sample java code provided doesn't even show how to read an image!

Answer

David Miguel picture David Miguel · Nov 6, 2016

To read an image with OpenCV for Java:

OpenCV 2.x (JavaDoc)

Mat img = Highgui.imread("path/to/img");

OpenCV 3.x (JavaDoc)

Mat img = Imgcodecs.imread("path/to/img");

In both versions you can pass a second parameter specifying how to load the image:

  • CV_LOAD_IMAGE_ANYDEPTH: returns 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit.
  • CV_LOAD_IMAGE_COLOR: always convert image to a color one.
  • CV_LOAD_IMAGE_GRAYSCALE: always convert image to a grayscale one.

Example:

// OpenCV 2.x   
Mat img = Highgui.imread("path/to/img", Highgui.CV_LOAD_IMAGE_GRAYSCALE);
// OpenCV 3.x
Mat img = Imgcodecs.imread("path/to/img", Imgcodecs.CV_LOAD_IMAGE_GRAYSCALE);