Ko.java Source code

Java tutorial

Introduction

Here is the source code for Ko.java

Source

/*
 * Copyright Jordan Schalm 2015
 * This program is distributed under the terms of the GNU General Public License.
 * 
 * This file is part of Ko.
 *
 * Ko is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Ko is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Ko.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

import org.opencv.core.*;
import org.opencv.highgui.Highgui;

/**
 * @author Jordan Schalm
 * 
 * Main class for Ko. Takes a single argument containing the filename
 * of the image to be scored.
 */
public class Ko {

    public static void main(String[] args) {
        String filename = args[0];
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        Mat original = Highgui.imread(filename);
        if (original.empty()) {
            System.out.println("Mat not successfully loaded.");
            System.exit(1);
        }
        KoBoard board = new KoBoard(original);
        saveImage(filename, original);
    }

    /**
     * Save the Mat image to a file with name = alt_ + filename.
     * @param filename
     *             The name of the original file.
     */
    private static void saveImage(String filename, Mat image) {
        BufferedImage imageWithOutlinedCircles = toBufferedImage(image);
        File f = new File("alt_" + filename);
        try {
            ImageIO.write(imageWithOutlinedCircles, "JPEG", f);
        } catch (IOException e) {
            System.out.println("Problem writing image to disk.");
        }

    }

    /**
    * Converts a cv::Mat to a BufferedImage so that it plays nicely 
    * with Java.
    * @param m
    *          The Mat to convert.
    * @return
    *          A BufferedImage version of the Mat.
    */
    private static BufferedImage toBufferedImage(Mat m) {
        int type = BufferedImage.TYPE_BYTE_GRAY;
        if (m.channels() > 1) {
            type = BufferedImage.TYPE_3BYTE_BGR;
        }
        int bufferSize = m.channels() * m.cols() * m.rows();
        byte b[] = new byte[bufferSize];
        m.get(0, 0, b);
        BufferedImage image = new BufferedImage(m.cols(), m.rows(), type);
        final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
        System.arraycopy(b, 0, targetPixels, 0, b.length);
        return image;
    }
}