0

I try to use the java bindings of open cv to apply an non-global contrast (histogram) optimization for a (color) png image, but I fail to get it to work.

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.File;

import javax.imageio.ImageIO;

import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.CLAHE;
import org.opencv.imgproc.Imgproc;


public class Main {
public static void main( String[] args ) {

   try {
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
      // fetch the png
      File input = new File("test.png");
      BufferedImage buffImage = ImageIO.read(input); 
      byte[] data = ((DataBufferByte) buffImage.getRaster().getDataBuffer()).getData();
      // build MAT for original image
      Mat orgImage = new Mat(buffImage.getHeight(),buffImage.getWidth(), CvType.CV_8UC3);
      orgImage.put(0, 0, data);
      // transform from to LAB
      Mat labImage = new Mat(buffImage.getHeight(), buffImage.getWidth(), CvType.CV_8UC4);
      Imgproc.cvtColor(orgImage, labImage, Imgproc.COLOR_BGR2Lab);


      // apply CLAHE
      CLAHE clahe = Imgproc.createCLAHE()
      Mat destImage = new Mat(buffImage.getHeight(),buffImage.getWidth(), CvType.CV_8UC4);
      clahe.apply(labImage, destImage);

      Imgcodecs.imwrite("test_clahe.png", destImage);
   } catch (Exception e) {
      System.out.println("Error: " + e.getMessage());
   }
   }

I get the exception:

Error: cv::Exception: C:\builds\master_PackSlaveAddon-win64-vc12-static\opencv\modules\imgproc\src\clahe.cpp:354: error: (-215) _src.type() == CV_8UC1 || _src.type() == CV_16UC1 in function `anonymous
-namespace'::CLAHE_Impl::apply

I guess I need to work with the individual channels, but I cannot figure out how. The code is inspired from this c++ example, but somehow I fail to extract the corresponding layers (I guess I need only L chanel for clahe.apply())

Raphael Roth
  • 26,751
  • 15
  • 88
  • 145

1 Answers1

1

This Example just splits the Lab image and applies Clahe on the L channel which is the intensity channel. So just use this code for java.

List<Mat> channels = new LinkedList();
Core.split(labImage, channels);
CLAHE clahe = Imgproc.createCLAHE()
Mat destImage = new Mat(buffImage.getHeight(),buffImage.getWidth(), CvType.CV_8UC4);
clahe.apply(channels.get(0), destImage);
Core.merge(channels, labImage);

and finally merge the intensity channel to the other channels. I haven't changed any parameters as I don't know how your image looks but I guess that isn't the problem. Hope it helps!

Martin
  • 3,703
  • 2
  • 21
  • 43
Rick M.
  • 3,045
  • 1
  • 21
  • 39