/**
   * Helper function to convert a Mat into a BufferedImage. Taken from
   * http://answers.opencv.org/question/10344/opencv-java-load-image-to-gui Author: 'Lucky Luke'
   *
   * @param matrix Mat of type CV_8UC3 or CV_8UC1
   * @return BufferedImage of type TYPE_3BYTE_BGR or TYPE_BYTE_GRAY
   */
  private static BufferedImage matToBufferedImage(Mat matrix) {
    int cols = matrix.cols();
    int rows = matrix.rows();
    int elemSize = (int) matrix.elemSize();
    byte[] data = new byte[cols * rows * elemSize];
    int type;

    matrix.get(0, 0, data);

    switch (matrix.channels()) {
      case 1:
        type = BufferedImage.TYPE_BYTE_GRAY;
        break;

      case 3:
        type = BufferedImage.TYPE_3BYTE_BGR;

        // bgr to rgb
        byte b;
        for (int i = 0; i < data.length; i = i + 3) {
          b = data[i];
          data[i] = data[i + 2];
          data[i + 2] = b;
        }
        break;

      default:
        return null;
    }

    BufferedImage image = new BufferedImage(cols, rows, type);
    image.getRaster().setDataElements(0, 0, cols, rows, data);

    return image;
  }
  public static void main(String[] args) {
    try {
      System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

      File input = new File("traffic_signal.jpg");
      BufferedImage image = ImageIO.read(input);

      byte[] data = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
      Mat mat = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC3);
      mat.put(0, 0, data);

      Mat mat1 = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC1);
      Imgproc.cvtColor(mat, mat1, Imgproc.COLOR_RGB2GRAY);

      byte[] data1 = new byte[mat1.rows() * mat1.cols() * (int) (mat1.elemSize())];
      mat1.get(0, 0, data1);
      BufferedImage image1 =
          new BufferedImage(mat1.cols(), mat1.rows(), BufferedImage.TYPE_BYTE_GRAY);
      image1.getRaster().setDataElements(0, 0, mat1.cols(), mat1.rows(), data1);

      File ouptut = new File("output\\grayscale_" + new Date().getTime() + ".jpg");
      ImageIO.write(image1, "jpg", ouptut);
    } catch (Exception e) {
      System.out.println("Error: " + e.getMessage());
    }
  }