Skip to content

Instantly share code, notes, and snippets.

@delabassee
Last active April 8, 2020 12:24
Show Gist options
  • Save delabassee/1ba380e1f32d20f2c518b1e6c6b080eb to your computer and use it in GitHub Desktop.
Save delabassee/1ba380e1f32d20f2c518b1e6c6b080eb to your computer and use it in GitHub Desktop.
import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import java.io.File;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
String info = "Java " + System.getProperty("java.version") + " "
+ Core.NATIVE_LIBRARY_NAME + Core.VERSION_STATUS;
System.out.println(info);
var filename = "duke.png";
var file = new File(filename);
if (!file.exists()) {
System.out.println(filename + "not found!");
System.exit(-1);
}
var srcImage = Imgcodecs.imread(filename, Imgcodecs.IMREAD_UNCHANGED);
List<Mat> channels = new ArrayList<>();
Core.split(srcImage, channels);
var chAlpha = channels.get(3); // 4th channel = Alpha
Imgproc.cvtColor(srcImage, srcImage, Imgproc.COLOR_BGRA2GRAY);
List<Mat> greyChannel = new ArrayList<>();
Core.split(srcImage, greyChannel);
var chGray = greyChannel.get(0);
var grayDuke = new Mat();
var listMat = Arrays.asList(chGray, chGray, chGray, chAlpha); // 3 channels + Alpha
Core.merge(listMat, grayDuke);
Imgcodecs.imwrite("duke_gray.png", grayDuke);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment