Q:

OpenCV in Java for Image Filtering

i have java codes from Tutorials Point. This code for Robinson filter.
package improctry2;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;

public class ImProcTry2 {
   public static void main( String[] args )
   {
   try {
      int kernelSize = 9;
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
      Mat source = Highgui.imread("grayscale.jpg",
      Highgui.CV_LOAD_IMAGE_GRAYSCALE);
      Mat destination = new Mat(source.rows(),source.cols(),source.type());
      Mat kernel = new Mat(kernelSize,kernelSize, CvType.CV_32F){
      {
         put(0,0,-1);
         put(0,1,0);
         put(0,2,1);

         put(1,0-2);
         put(1,1,0);
         put(1,2,2);

         put(2,0,-1);
         put(2,1,0);
         put(2,2,1);
      }
      };          
      Imgproc.filter2D(source, destination, -1, kernel);
      Highgui.imwrite("output.jpg", destination);
      } catch (Exception e) {
         System.out.println("Error: " + e.getMessage());
      }
   }
}     

This is is my image input, and this the output (i can't post the pictures because i'm new in stackoverflow).
As you can see, the image turn into black and nothing appears. I'm using Netbeans IDE 8.0 and i already put the OpenCV library in Netbeans. I also run another OpenCV Java codes and they work very well. And i also run this code in Eclipse but the result is same.
Anybody can help me?
Thank You

A:

You create a 9x9 kernel matrix, but then fill only a 3x3 submatrix of it, leaving other elements unititialized. To fix it, just change:
int kernelSize = 9;

to:
int kernelSize = 3;

Your code actually works in the newest Opencv (3.0 beta), but those unititialized elements break it in older versions (I checked 2.4.10). To print elements of a matrix use:
System.out.println(kernel.dump());

PS.
Welcome to stackoverflow. :)

