Opencv-quick-guide

提供:Dev Guides
移動先:案内検索

OpenCV-概要

OpenCVはクロスプラットフォームライブラリであり、これを使用してリアルタイムの*コンピュータービジョンアプリケーション*を開発できます。 主に画像処理、ビデオキャプチャ、および顔検出やオブジェクト検出などの機能を含む分析に焦点を当てています。

「コンピュータービジョン」という用語を定義して、この章を始めましょう。

コンピュータビジョン

コンピュータービジョンは、2D画像から3Dシーンを再構築、中断、および理解する方法を、シーンに存在する構造の特性の観点から説明する分野として定義できます。 コンピューターソフトウェアとハ​​ードウェアを使用して、人間の視覚のモデリングと複製を扱います。

コンピュータビジョンは、次のフィールドと大幅に重複しています-

  • 画像処理-画像操作に焦点を当てています。
  • パターン認識-パターンを分類するためのさまざまなテクニックを説明します。
  • 写真測量-画像から正確な測定値を取得することに関係しています。

コンピュータビジョンと画像処理

  • 画像処理*は、画像から画像への変換を処理します。 画像処理の入力と出力は両方とも画像です。
  • コンピュータービジョン*は、画像から物理オブジェクトの明示的で意味のある記述を作成することです。 コンピュータービジョンの出力は、3Dシーンの構造の説明または解釈です。

コンピュータビジョンの応用

ここでは、Computer Visionが頻繁に使用される主要なドメインの一部をリストしました。

ロボットアプリケーション

  • ローカリゼーション-ロボットの位置を自動的に決定する
  • ナビゲーション
  • 障害物回避
  • 組み立て(ペグインホール、溶接、塗装)
  • 操作(例: PUMAロボットマニピュレーター)
  • ヒューマンロボットインタラクション(HRI)-人とやり取りし、サービスを提供するインテリジェントロボット工学

医学の応用

  • 分類と検出(例: 病変または細胞の分類および腫瘍の検出)
  • 2D/3Dセグメンテーション
  • 3Dヒト臓器再建(MRIまたは超音波)
  • 視覚誘導ロボット手術

産業オートメーションアプリケーション

  • 産業検査(欠陥検出)
  • アセンブリ
  • バーコードおよびパッケージラベルの読み取り
  • オブジェクトの並べ替え
  • ドキュメントの理解(例: OCR)

セキュリティアプリケーション

  • 生体認証(虹彩、指紋、顔認識)
  • 監視-特定の不審な活動または行動の検出

輸送アプリケーション

  • 自律走行車
  • 安全性、例:ドライバーの警戒監視

OpenCVライブラリの機能

OpenCVライブラリを使用すると、次のことができます-

  • 画像の読み書き
  • ビデオをキャプチャして保存する
  • 画像の処理(フィルター、変換)
  • 特徴検出を実行する
  • ビデオや画像から顔、目、車などの特定のオブジェクトを検出します。
  • ビデオを分析します。つまり、ビデオの動きを推定し、背景を減算し、その中のオブジェクトを追跡します。

OpenCVはもともとC++で開発されました。 それに加えて、PythonおよびJavaバインディングが提供されました。 OpenCVは、Windows、Linux、OSx、FreeBSD、Net BSD、Open BSDなどのさまざまなオペレーティングシステムで実行されます。

このチュートリアルでは、Javaバインディングを使用した例でOpenCVの概念を説明します。

OpenCVライブラリモジュール

OpenCVライブラリの主要なライブラリモジュールは次のとおりです。

コア機能

このモジュールは、OpenCVアプリケーションの構築に使用されるスカラー、ポイント、範囲などの基本的なデータ構造をカバーしています。 これらに加えて、画像を保存するために使用される多次元配列 Mat も含まれます。 OpenCVのJavaライブラリでは、このモジュールは org.opencv.core という名前のパッケージとして含まれています。

画像処理

このモジュールは、画像フィルタリング、幾何学的画像変換、色空間変換、ヒストグラムなどのさまざまな画像処理操作をカバーしています。 OpenCVのJavaライブラリでは、このモジュールは org.opencv.imgproc という名前のパッケージとして含まれています。

ビデオ

このモジュールでは、モーション推定、バックグラウンド減算、オブジェクトトラッキングなどのビデオ分析の概念について説明します。 OpenCVのJavaライブラリでは、このモジュールは org.opencv.video という名前のパッケージとして含まれています。

ビデオI/O

このモジュールでは、OpenCVライブラリを使用したビデオキャプチャとビデオコーデックについて説明します。 OpenCVのJavaライブラリでは、このモジュールは org.opencv.videoio という名前のパッケージとして含まれています。

calib3d

このモジュールには、基本的なマルチビュージオメトリアルゴリズム、単一およびステレオカメラキャリブレーション、オブジェクトポーズ推定、ステレオ対応、3D再構成の要素に関するアルゴリズムが含まれています。 OpenCVのJavaライブラリでは、このモジュールは org.opencv.calib3d という名前のパッケージとして含まれています。

features2d

このモジュールには、機能の検出と説明の概念が含まれています。 OpenCVのJavaライブラリでは、このモジュールは org.opencv.features2d という名前のパッケージとして含まれています。

Objdetect

このモジュールには、オブジェクト、顔、目、マグカップ、人、車などの定義済みクラスのインスタンスの検出が含まれます。 OpenCVのJavaライブラリでは、このモジュールは org.opencv.objdetect という名前のパッケージとして含まれています。

ハイグイ

これは、シンプルなUI機能を備えた使いやすいインターフェイスです。 OpenCVのJavaライブラリでは、このモジュールの機能は、 org.opencv.imgcodecsorg.opencv.videoio の2つの異なるパッケージに含まれています。

OpenCVの簡単な歴史

OpenCVは当初、CPUを集中的に使用するアプリケーションに助言するためのIntelの研究イニシアチブでした。 1999年に正式に開始されました。

  • 2006年には、その最初のメジャーバージョンであるOpenCV 1.0がリリースされました。
  • 2009年10月、2番目のメジャーバージョンであるOpenCV 2がリリースされました。
  • 2012年8月、OpenCVは非営利団体OpenCV.orgに採用されました。

OpenCV-環境

この章では、OpenCVをインストールし、システムに環境を設定する方法を学びます。

OpenCVのインストール

まず、システムにOpenCVをダウンロードする必要があります。 以下の手順に従ってください。

ステップ1 *-次のリンクをクリックして、 *OpenCV のホームページを開きます。http://opencv.org/クリックすると、以下に示すようなホームページが表示されます。

OpenCV HomePage

  • ステップ2 *-次に、上記のスクリーンショットで強調表示されている*ダウンロード*リンクをクリックします。 クリックすると、OpenCVのダウンロードページに移動します。

OpenCVダウンロードページ

ステップ3 *-上記のスクリーンショットで強調表示されているリンクをクリックすると、 *opencv-3.1.0.exe という名前のファイルがダウンロードされます。 次のスクリーンショットに示すように、このファイルを解凍して、システムにフォルダー opencv を生成します。

ダウンロードされたOpenCV

ステップ4 *-フォルダ *OpenCVbuildjava を開きます。 ここに、 opencv-310.jar という名前のOpenCVのjarファイルがあります。 さらに使用するために、このファイルを別のフォルダーに保存します。

OpenCV Jarファイル

Eclipseのインストール

必要なJARファイルをダウンロードしたら、これらのJARファイルをEclipse環境に埋め込む必要があります。 これを行うには、ビルドパスをこれらのJARファイルに設定し、 pom.xml を使用します。

ビルドパスの設定

以下は、EclipseでOpenCVをセットアップする手順です-

  • ステップ1 *-システムにEclipseがインストールされていることを確認します。 そうでない場合は、システムにEclipseをダウンロードしてインストールします。
  • ステップ2 *-次のスクリーンショットに示すように、Eclipseを開き、[ファイル]、[新規]の順にクリックして、新しいプロジェクトを開きます。

Open Eclipse

ステップ3 *-プロジェクトを選択すると、*新しいプロジェクト*ウィザードが表示されます。 このウィザードで、Javaプロジェクトを選択し、次のスクリーンショットに示すように、 *Next ボタンをクリックして続行します。

プロジェクトの選択

  • ステップ4 *-先に進むと、*新しいJavaプロジェクトウィザード*に移動します。 次のスクリーンショットに示すように、新しいプロジェクトを作成し、[次へ]をクリックします。

新規Javaプロジェクトウィザード

ステップ5 *-新しいプロジェクトを作成した後、それを右クリックします。 次のスクリーンショットに示すように、 *Build Path を選択し、* Configure Build Path…*をクリックします。

ビルドパスの選択

ステップ6 *-*ビルドパス*オプションをクリックすると、 Javaビルドパスウィザード*が表示されます。 次のスクリーンショットに示すように、[外部JARの追加]ボタンをクリックします。

ビルドパスをクリック

ステップ7 *-ファイル *opencv-310.jar を保存したパスを選択します。

  • ステップ8 *-上記のスクリーンショットの*開く*ボタンをクリックすると、これらのファイルがライブラリに追加されます。

開くボタンをクリック

ステップ9 *- *OK をクリックすると、現在のプロジェクトに必要なJARファイルが正常に追加され、参照ライブラリを展開してこれらの追加ライブラリを確認できます。

OKをクリック

ネイティブライブラリのパスの設定

JARファイルに加えて、OpenCVのネイティブライブラリ(DLLファイル)のパスを設定する必要があります。

  • DLLファイルの場所*- OpenCV のインストールフォルダーを開き、サブフォルダー buildjava に移動します。 ここには、OpenCVの dll ファイルを含む2つのフォルダー x64 (64ビット)および x86 (32ビット)があります。

DLLファイルの場所

ご使用のオペレーティングシステムに適したフォルダーを開くと、次のスクリーンショットに示すように、 dll ファイルが表示されます。

フォルダーを開く

今、以下に示す手順に従って、このファイルのパスも設定します-

ステップ1 *-もう一度、JavaBuildPathウィンドウを開きます。 ここで、追加されたJARファイルと JREシステムライブラリ*を確認できます。

JREシステムライブラリ

  • ステップ2 *-展開すると、次のスクリーンショットで強調表示されているように、システムライブラリと*ネイティブライブラリの場所*が表示されます。

ネイティブライブラリの場所

  • ステップ3 *-*ネイティブライブラリの場所*をダブルクリックします。 ここでは、以下に示すように*ネイティブライブラリフォルダーの設定ウィンドウ*を見ることができます。

ネイティブライブラリの場所をダブルクリック

ここで、* External Folder…ボタンをクリックし、システム内の *dll ファイルの場所を選択します。

OpenCV-画像の保存

画像をキャプチャするには、カメラやスキャナーなどのデバイスを使用します。 これらのデバイスは、画像の数値を記録します(例:ピクセル値)。 OpenCVはデジタル画像を処理するライブラリです。したがって、処理のためにこれらの画像を保存する必要があります。

OpenCVライブラリの Mat クラスは、画像の値を格納するために使用されます。 n次元配列を表し、グレースケールまたはカラー画像の画像データ、ボクセルボリューム、ベクトルフィールド、点群、テンソル、ヒストグラムなどを格納するために使用されます。

このクラスは、2つのデータ部分で構成されます: header および pointer

  • ヘッダー-サイズ、格納に使用されるメソッド、およびマトリックスのアドレス(サイズが一定)などの情報が含まれます。
  • ポインタ-画像のピクセル値を保存します(変化し続ける)。

マットクラス

OpenCV Javaライブラリは、パッケージ org.opencv.core 内で同じ名前( Mat )でこのクラスを提供します。

コンストラクタ

OpenCV JavaライブラリのMatクラスには、Matオブジェクトを構築できるさまざまなコンストラクターがあります。

S.No Constructors and Description
1

Mat()

これはほとんどの場合、パラメーターのないデフォルトのコンストラクターです。 これをコンストラクタに使用して空の行列を作成し、これを他のOpenCVメソッドに渡します。

2

Mat(int rows, int cols, int type)

このコンストラクターは、2D配列の行と列の数と配列の型(データの保存に使用される)を表す整数型の3つのパラメーターを受け入れます。

3

Mat(int rows, int cols, int type, Scalar s)

前のパラメーターを含め、このコンストラクターはパラメーターとしてクラスScalarのオブジェクトを追加で受け入れます。

4

Mat(Size size, int type)

このコンストラクターは、2つのパラメーター、マトリックスのサイズを表すオブジェクトと、データの格納に使用される配列のタイプを表す整数を受け入れます。

5

Mat(Size size, int type, Scalar s)

前のパラメーターを含め、このコンストラクターはパラメーターとしてクラスScalarのオブジェクトを追加で受け入れます。

6 *Mat(long addr) *
7
  • Mat(Mat m, Range rowRange)*

このコンストラクタは、別のマトリックスのオブジェクトと、新しいマトリックスを作成するために取得する行の範囲を表すクラスRangeのオブジェクトを受け入れます。

8

Mat(Mat m, Range rowRange, Range colRange)

前のパラメーターを含めて、このコンストラクターはクラスのオブジェクトを追加で受け入れます。 列の範囲を表す範囲。

9

Mat(Mat m, Rect roi)

このコンストラクタは、2つのオブジェクトを受け入れます。1つは別のマトリックスを表し、もう1つは* R egion O f I * nestestを表します。

-

  • 配列タイプ。 CV_8UC1、…​、CV_64FC4を使用して1〜4チャンネルのマトリックスを作成するか、CV_8UC(n)、…​、CV_64FC(n)を使用してマルチチャンネル(最大CV_CN_MAXチャンネル)のマトリックスを作成します。
  • マトリックスのタイプは、パッケージ org.opencv.core に属するクラス CvType のさまざまなフィールドによって表されていました。

メソッドと説明

以下は、Matクラスによって提供されるメソッドの一部です。

S.No Methods and Description
1

Mat col(int x)

このメソッドは、列のインデックスを表す整数パラメーターを受け入れ、その列を取得して返します。

2

Mat row(int y)

このメソッドは、行のインデックスを表す整数パラメーターを受け入れ、その行を取得して返します。

3

int cols()

このメソッドは、マトリックスの列数を返します。

4

int rows()

このメソッドは、マトリックス内の行数を返します。

5

Mat setTo(Mat value)

このメソッドは、 Mat タイプのオブジェクトを受け入れ、配列要素を指定された値に設定します。

6

Mat setTo(Scalar s)

このメソッドは、 Scalar タイプのオブジェクトを受け入れ、配列要素を指定された値に設定します。

マトリックスの作成と表示

このセクションでは、最初のOpenCVの例について説明します。 簡単なOpenCVマトリックスを作成して表示する方法を見ていきます。

以下に、OpenCVでマトリックスを作成して表示するために従うべき手順を示します。

ステップ1:OpenCVネイティブライブラリをロードする

OpenCVライブラリを使用してJavaコードを作成する場合、最初に行う必要があるステップは、* loadLibrary()*を使用してOpenCVのネイティブライブラリをロードすることです。 以下に示すように、OpenCVネイティブライブラリをロードします。

//Loading the core library
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

ステップ2:Matクラスをインスタンス化する

この章で前述した関数のいずれかを使用して、Matクラスをインスタンス化します。

//Creating a matrix
Mat matrix = new Mat(5, 5, CvType.CV_8UC1, new Scalar(0));

ステップ3:メソッドを使用してマトリックスを埋める

メソッド* row()/col()*にインデックス値を渡すことで、マトリックスの特定の行/列を取得できます。

また、* setTo()*メソッドのバリアントのいずれかを使用して、これらに値を設定できます。

//Retrieving the row with index 0
Mat row0 = matrix.row(0);

//setting values of all elements in the row with index 0
row0.setTo(new Scalar(1));

//Retrieving the row with index 3
Mat col3 = matrix.col(3);

//setting values of all elements in the row with index 3
col3.setTo(new Scalar(3));

次のプログラムコードを使用して、OpenCVライブラリを使用してJavaで単純なマトリックスを作成および表示できます。

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.CvType;
import org.opencv.core.Scalar;

class DisplayingMatrix {
   public static void main(String[] args) {
     //Loading the core library
      System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

     //Creating a matrix
      Mat matrix = new Mat(5, 5, CvType.CV_8UC1, new Scalar(0));

     //Retrieving the row with index 0
      Mat row0 = matrix.row(0);

     //setting values of all elements in the row with index 0
      row0.setTo(new Scalar(1));

     //Retrieving the row with index 3
      Mat col3 = matrix.col(3);

     //setting values of all elements in the row with index 3
      col3.setTo(new Scalar(3));

     //Printing the matrix
      System.out.println("OpenCV Mat data:\n" + matrix.dump());
   }
}

上記のプログラムを実行すると、次の出力が得られます-

OpenCV Mat data:
[  1,   1,   1,   3,   1;
   0,   0,   0,   3,   0;
   0,   0,   0,   3,   0;
   0,   0,   0,   3,   0;
   0,   0,   0,   3,   0]

JavaSE APIを使用した画像の読み込み

*java.awt.image.BufferedImage* パッケージの *BufferedImage* クラスは画像の保存に使用され、パッケージの *ImageIO* クラスは *import javax.imageio* が画像を読み書きするメソッドを提供します。

次のプログラムコードを使用して、JavaSEライブラリを使用してイメージをロードおよび保存できます。

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

public class LoadingImage_JSE_library {
   public static void main( String[] args ) throws IOException {
     //Input File
      File input = new File("C:/EXAMPLES/OpenCV/sample.jpg");

     //Reading the image
      BufferedImage image = ImageIO.read(input);

     //Saving the image with a different name
      File ouptut = new File("C:/OpenCV/sample.jpg");
      ImageIO.write(image, "jpg", ouptut);

      System.out.println("image Saved");
   }
}

上記のプログラムを実行すると、次の出力が得られます-

image Saved

あなたが指定されたパスを開いた場合、次のように保存された画像を観察することができます-

JavaSE APIを使用した画像の読み込み

OpenCV-画像の読み取り

パッケージ org.opencv.imgcodecsImgcodecs クラスは、画像を読み書きするメソッドを提供します。 OpenCVを使用すると、画像を読み取ってマトリックスに保存できます(必要に応じて、マトリックスで変換を実行します)。 後で、処理されたマトリックスをファイルに書き込むことができます。

*Imgcodecs* クラスの* read()*メソッドは、OpenCVを使用して画像を読み取るために使用されます。 このメソッドの構文は次のとおりです。
imread(filename)

引数*(filename)*を受け入れます。これは、読み取られるファイルのパスを表すString型の変数です。

以下に、OpenCVライブラリを使用してJavaで画像を読み取る手順を示します。

ステップ1:OpenCVネイティブライブラリをロードする

以下に示すように、* load()*メソッドを使用してOpenCVネイティブライブラリをロードします。

//Loading the core library
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

ステップ2:Imgcodecsクラスをインスタンス化する

*Imgcodecs* クラスをインスタンス化します。
//Instantiating the Imgcodecs class
Imgcodecs imageCodecs = new Imgcodecs();

ステップ3:画像を読む

メソッド* imread()を使用して画像を読み取ります。 このメソッドは、画像のパスを表す文字列引数を受け入れ、 *Mat オブジェクトとして読み取られた画像を返します。

//Reading the Image from the file
Mat matrix = imageCodecs.imread(Path of the image);

次のプログラムコードは、OpenCVライブラリを使用して*画像を読み取る*方法を示しています。

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;

public class ReadingImages {
   public static void main(String args[]) {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Instantiating the Imagecodecs class
      Imgcodecs imageCodecs = new Imgcodecs();

     //Reading the Image from the file
      String file ="C:/EXAMPLES/OpenCV/sample.jpg";
      Mat matrix = imageCodecs.imread(file);

      System.out.println("Image Loaded");
   }
}

上記のプログラムを実行すると、OpenCVは指定された画像をロードし、次の出力を表示します-

Image Loaded

OpenCV-画像を書く

*Imgcodecs* クラスの* write()*メソッドは、OpenCVを使用して画像を書き込むために使用されます。 画像を書き込むには、前の例の最初の3つの手順を繰り返します。

イメージを書き込むには、 Imgcodecs クラスの* imwrite()*メソッドを呼び出す必要があります。

このメソッドの構文は次のとおりです。

imwrite(filename, mat)

このメソッドは、次のパラメータを受け入れます-

  • filename -ファイルを保存するパスを表す String 変数。
  • mat -書き込まれる画像を表す Mat オブジェクト。

次のプログラムは、OpenCVライブラリを使用してJavaプログラムを使用して*画像を書き込む*例です。

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;

public class WritingImages {
   public static void main(String args[]) {
     //Loading the OpenCV core library
      System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

     //Instantiating the imagecodecs class
      Imgcodecs imageCodecs = new Imgcodecs();

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="C:/EXAMPLES/OpenCV/sample.jpg";
      Mat matrix = imageCodecs.imread(file);

      System.out.println("Image Loaded ..........");
      String file2 = "C:/EXAMPLES/OpenCV/sample_resaved.jpg";

     //Writing the image
      imageCodecs.imwrite(file2, matrix);
      System.out.println("Image Saved ............");
   }
}

上記のプログラムを実行すると、次の出力が得られます-

Image Loaded ..........
Image Saved ...........

あなたが指定されたパスを開くと、以下に示すように保存された画像を観察することができます-

イメージの書き込み

OpenCV-GUI

前の章で、OpenCV Javaライブラリを使用して画像を読み込んで保存する方法について説明しました。 それに加えて、AWT/SwingsやJavaFXなどのGUIライブラリを使用して、読み込んだ画像を別のウィンドウに表示することもできます。

マットをバッファリングされたイメージに変換する

画像を読み取るには、メソッド* imread()を使用します。 このメソッドは、読み取った画像を *Matrix の形式で返します。 ただし、このイメージをGUIライブラリ(AWT/SwingsおよびJavaFX)で使用するには、パッケージ java.awt.image.BufferedImage のクラス BufferedImage のオブジェクトとして変換する必要があります。

以下は、OpenCVの Mat オブジェクトを BufferedImage オブジェクトに変換する手順です。

ステップ1:MatをMatOfByteにエンコードする

まず、行列をバイトの行列に変換する必要があります。 クラス Imgcodecs のメソッド* imencode()*を使用して実行できます。 このメソッドの構文は次のとおりです。

imencode(ext, image, matOfByte);

このメソッドは、次のパラメータを受け入れます-

  • Ext -画像形式(.jpg、.pngなど)を指定する文字列パラメーター
  • image -画像のマットオブジェクト
  • matOfByte -クラスMatOfByteの空のオブジェクト

以下に示すように、この方法を使用して画像をエンコードします。

//Reading the image
Mat image = Imgcodecs.imread(file);

//instantiating an empty MatOfByte class
MatOfByte matOfByte = new MatOfByte();

//Converting the Mat object to MatOfByte
Imgcodecs.imencode(".jpg", image, matOfByte);

ステップ2:MatOfByteオブジェクトをバイト配列に変換する

メソッド* toArray()を使用して、 *MatOfByte オブジェクトをバイト配列に変換します。

byte[] byteArray = matOfByte.toArray();

ステップ3:InputStreamオブジェクトの準備

前の手順で作成したバイト配列を ByteArrayInputStream クラスのコンストラクターに渡すことにより、InputStreamオブジェクトを準備します。

//Preparing the InputStream object
InputStream in = new ByteArrayInputStream(byteArray);

ステップ4:InputStreamオブジェクトの準備

前の手順で作成した入力ストリームオブジェクトを ImageIO クラスの* read()*メソッドに渡します。 これは、BufferedImageオブジェクトを返します。

//Preparing the BufferedImage
BufferedImage bufImage = ImageIO.read(in);

AWT/Swingsを使用した画像の表示

AWT/Swingsフレームを使用して画像を表示するには、まず、* imread()メソッドを使用して画像を読み取り、上記の手順に従って *BufferedImage に変換します。

次に、 JFrame クラスをインスタンス化し、以下に示すように、JFrameのContentPaneに作成されたバッファー画像を追加します-

//Instantiate JFrame
JFrame frame = new JFrame();

//Set Content to the JFrame
frame.getContentPane().add(new JLabel(new ImageIcon(bufImage)));
frame.pack();
frame.setVisible(true);

次のプログラムコードは、OpenCVライブラリを使用して、画像を*読み取り*、スイングウィンドウで*表示*する方法を示しています。

import java.awt.image.BufferedImage;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;

public class DisplayingImagesUsingSwings {
   public static void main(String args[]) throws Exception {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file = "C:/EXAMPLES/OpenCV/sample.jpg";
      Mat image = Imgcodecs.imread(file);

     //Encoding the image
      MatOfByte matOfByte = new MatOfByte();
      Imgcodecs.imencode(".jpg", image, matOfByte);

     //Storing the encoded Mat in a byte array
      byte[] byteArray = matOfByte.toArray();

     //Preparing the Buffered Image
      InputStream in = new ByteArrayInputStream(byteArray);
      BufferedImage bufImage = ImageIO.read(in);

     //Instantiate JFrame
      JFrame frame = new JFrame();

     //Set Content to the JFrame
      frame.getContentPane().add(new JLabel(new ImageIcon(bufImage)));
      frame.pack();
      frame.setVisible(true);

      System.out.println("Image Loaded");
   }
}

上記のプログラムを実行すると、次の出力が得られます-

Image Loaded

それに加えて、次のように、ロードされた画像を表示するウィンドウを見ることができます-

Swingsを使用した画像の表示

JavaFXを使用した画像の表示

JavaFXを使用して画像を表示するには、まず* imread()メソッドを使用して画像を読み取り、それを *BufferedImage に変換します。 次に、以下に示すように、BufferedImageをWritableImageに変換します。

WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);

この WritableImage オブジェクトを ImageView クラスのコンストラクターに渡します。

ImageView imageView = new ImageView(writableImage);

次のプログラムコードは、OpenCVライブラリを使用して、JavaFXウィンドウで画像を*読み取り* *表示*する方法を示しています。

import java.awt.image.BufferedImage;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;

import javax.imageio.ImageIO;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;

public class DisplayingImagesJavaFX extends Application {
   @Override
   public void start(Stage stage) throws IOException {
      WritableImage writableImage = loadImage();

     //Setting the image view
      ImageView imageView = new ImageView(writableImage);

     //Setting the position of the image
      imageView.setX(50);
      imageView.setY(25);

     //setting the fit height and width of the image view
      imageView.setFitHeight(400);
      imageView.setFitWidth(500);

     //Setting the preserve ratio of the image view
      imageView.setPreserveRatio(true);

     //Creating a Group object
      Group root = new Group(imageView);

     //Creating a scene object
      Scene scene = new Scene(root, 600, 400);

     //Setting title to the Stage
      stage.setTitle("Loading an image");

     //Adding scene to the stage
      stage.setScene(scene);

     //Displaying the contents of the stage
      stage.show();
   }
   public WritableImage loadImage() throws IOException {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="C:/EXAMPLES/OpenCV/sample.jpg";
      Mat image = Imgcodecs.imread(file);

     //Encoding the image
      MatOfByte matOfByte = new MatOfByte();
      Imgcodecs.imencode(".jpg", image, matOfByte);

     //Storing the encoded Mat in a byte array
      byte[] byteArray = matOfByte.toArray();

     //Displaying the image
      InputStream in = new ByteArrayInputStream(byteArray);
      BufferedImage bufImage = ImageIO.read(in);

      System.out.println("Image Loaded");
      WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);
      return writableImage;
   }
   public static void main(String args[]) {
      launch(args);
   }
}

上記のプログラムを実行すると、次の出力が得られます-

Image Loaded

それに加えて、次のように、ロードされた画像を表示するウィンドウを見ることができます-

JavaFXを使用した画像の表示

OpenCV-IMREAD_XXXフラグ

OpenCVは、カラー、バイナリ、グレースケールなどのさまざまなタイプの画像をサポートしています。 * imread()メソッドと *Imgcodecs クラスの定義済みフィールドを使用して、特定の画像を別のタイプとして読み取ることができます。

imread()メソッドのflagsパラメーター(IMREAD_XXX)

前の章で、 Imgcodecs クラスの* imread()*メソッドの構文を見てきました。 読み取られるイメージの場所を表す文字列引数を受け入れます。

imread(filename)
  • imread()*メソッドには別の構文があります。
imread(filename, int flags)

この構文は2つのパラメータを受け入れます-

  • filename -引数*(filename)*、読み取り対象のファイルのパスを表すString型の変数を受け入れます。
  • flags -定義済みのフラグ値を表す整数値。 値ごとに、これは特定のタイプ(グレースケールカラーなど)として特定の画像を読み取ります。

以下は、このパラメーターの値として Imgproc クラスで提供されるさまざまなフィールドをリストした表です。

S.No Fields and Description
1

IMREAD_COLOR

フラグがこの値に設定されている場合、読み込まれた画像は3チャンネルBGR(青緑赤)カラー画像に変換されます。

2

IMREAD_GRAYSCALE

フラグがこの値に設定されている場合、読み込まれた画像はシングルチャンネルのグレースケール画像に変換されます。

3

IMREAD_LOAD_GDAL

フラグがこの値に設定されている場合、 gdal ドライバーを使用して画像をロードできます。

4

IMREAD_ANYCOLOR

フラグがこの値に設定されている場合、画像は可能なカラー形式で読み取られます。

5

IMREAD_REDUCED_COLOR_2

  • IMREAD_REDUCED_COLOR_4* *IMREAD_REDUCED_COLOR_8*

フラグがこの値に設定されている場合、画像は3チャネルBGRとして読み取られ、画像のサイズは、画像の元のサイズの½、¼^ th ^または⅛ ^ th ^に縮小されます。使用されるフィールド。

6

IMREAD_REDUCED_GRAYSCALE_2

  • IMREAD_REDUCED_GRAYSCALE_4* *IMREAD_REDUCED_GRAYSCALE_8*

フラグがこの値に設定されている場合、画像は単一チャネルのグレースケール画像として読み取られ、画像のサイズは元の画像のサイズの1/2、¼^ th ^または⅛ ^ th ^に縮小されます。使用されるフィールドに関して。

7

IMREAD_UNCHANGED

フラグがこの値に設定されている場合、ロードされたイメージはそのまま返されます。

OpenCV-画像をグレースケールとして読み取る

次のプログラムは、カラー画像をグレースケールとして読み取り、JavaFXウィンドウを使用して表示する方法を示しています。 ここでは、フラグ IMREAD_GRAYSCALE を色付きの画像のパスを保持する文字列と共に渡すことで画像を読み取りました。

import java.awt.image.BufferedImage;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;

public class ReadingAsGrayscale extends Application {
   @Override
   public void start(Stage stage) throws Exception {
      WritableImage writableImage = loadAndConvert();

     //Setting the image view
      ImageView imageView = new ImageView(writableImage);

     //Setting the position of the image
      imageView.setX(10);
      imageView.setY(10);

     //setting the fit height and width of the image view
      imageView.setFitHeight(400);
      imageView.setFitWidth(600);

     //Setting the preserve ratio of the image view
      imageView.setPreserveRatio(true);

     //Creating a Group object
      Group root = new Group(imageView);

     //Creating a scene object
      Scene scene = new Scene(root, 600, 400);

     //Setting title to the Stage
      stage.setTitle("Reading image as grayscale");

     //Adding scene to the stage
      stage.setScene(scene);

     //Displaying the contents of the stage
      stage.show();
   }
   public WritableImage loadAndConvert() throws Exception {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Instantiating the imagecodecs class
      Imgcodecs imageCodecs = new Imgcodecs();

      String input = "C:/EXAMPLES/OpenCV/sample.jpg";

     //Reading the image
      Mat src = imageCodecs.imread(input, Imgcodecs.IMREAD_GRAYSCALE);

      byte[] data1 = new byte[src.rows() *src.cols()* (int)(src.elemSize())];
      src.get(0, 0, data1);

     //Creating the buffered image
      BufferedImage bufImage = new BufferedImage(src.cols(),src.rows(),
         BufferedImage.TYPE_BYTE_GRAY);

     //Setting the data elements to the image
      bufImage.getRaster().setDataElements(0, 0, src.cols(), src.rows(), data1);

     //Creating a WritableImage
      WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);
      System.out.println("Image Read");
      return writableImage;
   }
   public static void main(String args[]) throws Exception {
      launch(args);
   }
}

入力画像

上記のプログラムで指定された入力画像 sample.jpg が次のものであると仮定します。

サンプル画像

出力画像

プログラムを実行すると、次の出力が得られます。

GrayScale出力画像

OpenCV-BGRとしての画像の読み取り

次のプログラムは、カラー画像をBGRタイプの画像として読み取り、JavaFXウィンドウを使用して表示する方法を示しています。 ここでは、フラグ IMREAD_COLOR をメソッド* imread()*にカラー画像のパスを保持する文字列とともに渡すことで画像を読み取りました。

import java.awt.image.BufferedImage;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;

public class ReadingAsColored extends Application {
   @Override
   public void start(Stage stage) throws Exception {
      WritableImage writableImage = loadAndConvert();

     //Setting the image view
      ImageView imageView = new ImageView(writableImage);

     //Setting the position of the image
      imageView.setX(10);
      imageView.setY(10);

     //setting the fit height and width of the image view
      imageView.setFitHeight(400);
      imageView.setFitWidth(600);

     //Setting the preserve ratio of the image view
      imageView.setPreserveRatio(true);

     //Creating a Group object
      Group root = new Group(imageView);

     //Creating a scene object
      Scene scene = new Scene(root, 600, 400);

     //Setting title to the Stage
      stage.setTitle("Reading as colored image");

     //Adding scene to the stage
      stage.setScene(scene);

     //Displaying the contents of the stage
      stage.show();
   }
   public WritableImage loadAndConvert() throws Exception {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

      String input = "C:/EXAMPLES/OpenCV/sample.jpg";

      Mat dst = new Mat();

     //Reading the image
      Mat src = Imgcodecs.imread(input, Imgcodecs.IMREAD_COLOR);

      byte[] data1 = new byte[src.rows() *src.cols()* (int)(src.elemSize())];
      src.get(0, 0, data1);

     //Creating the buffered image
      BufferedImage bufImage = new BufferedImage(src.cols(),src.rows(),
         BufferedImage.TYPE_3BYTE_BGR);

     //Setting the data elements to the image
      bufImage.getRaster().setDataElements(0, 0, src.cols(), src.rows(), data1);

     //Creating a WritableImage
      WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);

      System.out.println("Image read");
      return writableImage;
   }
   public static void main(String args[]) throws Exception {
      launch(args);
   }
}

入力画像

上記のプログラムで指定された入力画像 sample.jpg が次のものであると仮定します。

サンプル画像

出力画像

プログラムを実行すると、次の出力が得られます。

BGR出力画像

OpenCV-カラー画像をグレースケールに

前の章で、入力画像をさまざまなタイプ(バイナリ、グレースケール、BGRなど)として読み取る方法について説明しました。 この章では、あるタイプの画像を別のタイプに変換する方法を学びます。

パッケージ org.opencv.imgprocImgproc という名前のクラスは、画像をある色から別の色に変換するメソッドを提供します。

カラー画像をグレースケールに変換する

  • cvtColor()*という名前のメソッドは、カラー画像をグレースケールに変換するために使用されます。 このメソッドの構文は次のとおりです。
cvtColor(Mat src, Mat dst, int code)

このメソッドは、次のパラメータを受け入れます-

  • src -ソースを表す行列。
  • dst -宛先を表す行列。
  • code -RGBからグレースケールなど、変換のタイプを表す整数コード。

コード Imgproc.COLOR_RGB2GRAY を* cvtColor()*メソッドのパラメーターとしてソースおよび宛先マトリックスとともに渡すことにより、カラー画像をグレースケールに変換できます。

次のプログラムは、カラー画像をグレースケール画像として読み取り、JavaFXウィンドウを使用して表示する方法を示しています。

import java.awt.image.BufferedImage;

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

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;

import javafx.stage.Stage;

public class ColorToGrayscale extends Application {
   @Override
   public void start(Stage stage) throws Exception {
      WritableImage writableImage = loadAndConvert();

     //Setting the image view
      ImageView imageView = new ImageView(writableImage);

     //Setting the position of the image
      imageView.setX(10);
      imageView.setY(10);

     //setting the fit height and width of the image view
      imageView.setFitHeight(400);
      imageView.setFitWidth(600);

     //Setting the preserve ratio of the image view
      imageView.setPreserveRatio(true);

     //Creating a Group object
      Group root = new Group(imageView);

     //Creating a scene object
      Scene scene = new Scene(root, 600, 400);

     //Setting title to the Stage
      stage.setTitle("Colored to grayscale image");

     //Adding scene to the stage
      stage.setScene(scene);

     //Displaying the contents of the stage
      stage.show();
   }
   public WritableImage loadAndConvert() throws Exception {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

      String input = "C:/EXAMPLES/OpenCV/sample.jpg";

     //Reading the image
      Mat src = Imgcodecs.imread(input);

     //Creating the empty destination matrix
      Mat dst = new Mat();

     //Converting the image to gray sacle and saving it in the dst matrix
      Imgproc.cvtColor(src, dst, Imgproc.COLOR_RGB2GRAY);

     //Extracting data from the transformed image (dst)
      byte[] data1 = new byte[dst.rows() *dst.cols()* (int)(dst.elemSize())];
      dst.get(0, 0, data1);

     //Creating Buffered image using the data
      BufferedImage bufImage = new BufferedImage(dst.cols(),dst.rows(),
         BufferedImage.TYPE_BYTE_GRAY);

     //Setting the data elements to the image
      bufImage.getRaster().setDataElements(0, 0, dst.cols(), dst.rows(), data1);

     //Creating a WritableImage
      WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);
      System.out.println("Converted to Grayscale");
      return writableImage;
   }
   public static void main(String args[]) throws Exception {
      launch(args);
   }
}

入力画像

上記のプログラムで指定された入力画像 sample.jpg が次のものであると仮定します。

サンプル画像

出力画像

プログラムを実行すると、次の出力が得られます。

グレースケール出力へのカラー画像

OpenCV-カラー画像をバイナリに

  • threshold()*というメソッドを使用して、グレースケール画像をバイナリ画像に変換します。 このメソッドの構文は次のとおりです。
threshold(Mat src, Mat dst, double thresh, double maxval, int type)

このメソッドは、次のパラメータを受け入れます-

  • mat -入力画像を表す Mat オブジェクト。
  • dst -出力画像を表す Mat オブジェクト。
  • thresh -しきい値を表す整数。
  • maxval -THRESH_BINARYおよびTHRESH_BINARY_INVしきい値タイプで使用する最大値を表す整数。
  • type -RGBからグレースケールなど、変換のタイプを表す整数コード。

コード Imgproc.THRESH_BINARY を値とともに残りのパラメーターに渡すことにより、グレースケールイメージをバイナリイメージに変換できます。

次のプログラムは、カラー画像をバイナリ画像として読み取り、JavaFXウィンドウを使用して表示する方法を示しています。

import java.awt.image.BufferedImage;

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

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;

public class ColorToBinary extends Application {
   @Override
   public void start(Stage stage) throws Exception {
      WritableImage writableImage = loadAndConvert();

     //Setting the image view
      ImageView imageView = new ImageView(writableImage);

     //Setting the position of the image
      imageView.setX(10);
      imageView.setY(10);

     //setting the fit height and width of the image view
      imageView.setFitHeight(400);
      imageView.setFitWidth(600);

     //Setting the preserve ratio of the image view
      imageView.setPreserveRatio(true);

     //Creating a Group object
      Group root = new Group(imageView);

     //Creating a scene object
      Scene scene = new Scene(root, 600, 400);

     //Setting title to the Stage
      stage.setTitle("Loading an image");

     //Adding scene to the stage
      stage.setScene(scene);

     //Displaying the contents of the stage
      stage.show();
   }
   public WritableImage loadAndConvert() throws Exception {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Instantiating the Imgcodecs class
      Imgcodecs imageCodecs = new Imgcodecs();

     //File input = new File("C:/EXAMPLES/OpenCV/sample.jpg");
      String input = "C:/EXAMPLES/OpenCV/sample.jpg";

     //Reading the image
      Mat src = imageCodecs.imread(input);

     //Creating the destination matrix
      Mat dst = new Mat();

     //Converting to binary image...
      Imgproc.threshold(src, dst, 200, 500, Imgproc.THRESH_BINARY);

     //Extracting data from the transformed image (dst)
      byte[] data1 = new byte[dst.rows() *dst.cols()* (int)(dst.elemSize())];
      dst.get(0, 0, data1);

     //Creating Buffered image using the data
      BufferedImage bufImage = new BufferedImage(dst.cols(),dst.rows(),
         BufferedImage.TYPE_BYTE_GRAY);

     //Setting the data elements to the image
      bufImage.getRaster().setDataElements(0, 0, dst.cols(), dst.rows(), data1);

     //Creating a Writable image
      WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);

      System.out.println("Converted to binary");
      return writableImage;
   }
   public static void main(String args[]) throws Exception {
      launch(args);
   }
}

入力画像

上記のプログラムで指定された入力画像 sample.jpg が次のものであると仮定します。

サンプル画像

出力画像

プログラムを実行すると、次の出力が得られます。

カラー画像からバイナリ出力

OpenCV-グレースケールからバイナリ

前の章で説明したのと同じ方法を使用して、グレースケール画像をバイナリ画像に変換できます。 このプログラムへの入力としてグレースケール画像のパスを渡すだけです。

次のプログラムは、グレースケール画像をバイナリ画像として読み取り、JavaFXウィンドウを使用して表示する方法を示しています。

import java.awt.image.BufferedImage;

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

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;

public class GrayScaleToBinary extends Application {
   @Override
   public void start(Stage stage) throws Exception {
      WritableImage writableImage = loadAndConvert();

     //Setting the image view
      ImageView imageView = new ImageView(writableImage);

     //Setting the position of the image
      imageView.setX(10);
      imageView.setY(10);

     //Setting the fit height and width of the image view
      imageView.setFitHeight(400);
      imageView.setFitWidth(600);

     //Setting the preserve ratio of the image view
      imageView.setPreserveRatio(true);

     //Creating a Group object
      Group root = new Group(imageView);

     //Creating a scene object
      Scene scene = new Scene(root, 600, 400);

     //Setting title to the Stage
      stage.setTitle("Grayscale to binary image");

     //Adding scene to the stage
      stage.setScene(scene);

     //Displaying the contents of the stage
      stage.show();
   }
   public WritableImage loadAndConvert() throws Exception {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Instantiating the imagecodecs class
      Imgcodecs imageCodecs = new Imgcodecs();

      String input = "E:/OpenCV/chap7/grayscale.jpg";

     //Reading the image
      Mat src = imageCodecs.imread(input);

     //Creating the destination matrix
      Mat dst = new Mat();

     //Converting to binary image...
      Imgproc.threshold(src, dst, 200, 500, Imgproc.THRESH_BINARY);

     //Extracting data from the transformed image (dst)
      byte[] data1 = new byte[dst.rows() *dst.cols()* (int)(dst.elemSize())];
      dst.get(0, 0, data1);

     //Creating Buffered image using the data
      BufferedImage bufImage = new BufferedImage(dst.cols(),dst.rows(),
         BufferedImage.TYPE_BYTE_BINARY);

     //Setting the data elements to the image
      bufImage.getRaster().setDataElements(0, 0, dst.cols(), dst.rows(), data1);

     //Creating a Writable image
      WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);

      System.out.println("Converted to binary");
      return writableImage;
   }
   public static void main(String args[]) throws Exception {
      launch(args);
   }
}

入力画像

上記のプログラムで指定された入力画像 sample.jpg が次のものであると仮定します。

サンプル画像

出力画像

プログラムを実行すると、次の出力が得られます。

GrayScale to Binary

OpenCV-円を描く

*org.opencv.imgproc* パッケージの各メソッドを使用して、画像上に円、長方形、線、楕円、ポリライン、凸、ポリライン、ポリラインなどのさまざまな形状を描画できます。
*imgproc* クラスの* circle()*メソッドを使用して、画像に円を描くことができます。 以下は、このメソッドの構文です-
circle(img, center, radius, color, thickness)

このメソッドは、次のパラメータを受け入れます-

  • mat -円が描かれる画像を表す Mat オブジェクト。
  • point -円の中心を表す Point オブジェクト。
  • 半径-円の半径を表す*整数*型の変数。
  • scalar -円の色を表す Scalar オブジェクト。 (BGR)
  • thickness -円の太さを表す*整数*。デフォルトでは、厚さの値は1です。

次のプログラムは、画像に円を描き、JavaFXウィンドウを使用して表示する方法を示しています。

import java.awt.image.BufferedImage;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class DrawingCircle extends Application {
   Mat matrix = null;

   @Override
   public void start(Stage stage) throws Exception {
     //Capturing the snapshot from the camera
      DrawingCircle obj = new DrawingCircle();
      WritableImage writableImage = obj.LoadImage();

     //Setting the image view
      ImageView imageView = new ImageView(writableImage);

     //setting the fit height and width of the image view
      imageView.setFitHeight(600);
      imageView.setFitWidth(600);

     //Setting the preserve ratio of the image view
      imageView.setPreserveRatio(true);

     //Creating a Group object
      Group root = new Group(imageView);

     //Creating a scene object
      Scene scene = new Scene(root, 600, 400);

     //Setting title to the Stage
      stage.setTitle("Drawing Circle on the image");

     //Adding scene to the stage
      stage.setScene(scene);

     //Displaying the contents of the stage
      stage.show();
   }
   public WritableImage LoadImage() throws Exception {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap8/input.jpg";
      Mat matrix = Imgcodecs.imread(file);

     //Drawing a Circle
      Imgproc.circle (
         matrix,                //Matrix obj of the image
         new Point(230, 160),   //Center of the circle
         100,                   //Radius
         new Scalar(0, 0, 255), //Scalar object for color
         10                     //Thickness of the circle
      );

     //Encoding the image
      MatOfByte matOfByte = new MatOfByte();
      Imgcodecs.imencode(".jpg", matrix, matOfByte);

     //Storing the encoded Mat in a byte array
      byte[] byteArray = matOfByte.toArray();

     //Displaying the image
      InputStream in = new ByteArrayInputStream(byteArray);
      BufferedImage bufImage = ImageIO.read(in);
      this.matrix = matrix;

     //Creating the Writable Image
      WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);

      return writableImage;
   }
   public static void main(String args[]) {
      launch(args);
   }
}

上記のプログラムを実行すると、次の出力が得られます-

円を描く

OpenCV-線の描画

*imgproc* クラスの* line()*メソッドを使用して、画像上に線を描画できます。 このメソッドの構文は次のとおりです。
line(img, pt1, pt2, color, thickness)

このメソッドは、次のパラメータを受け入れます-

  • mat -線が描かれる画像を表す Mat オブジェクト。
  • pt1およびpt2 -線を引くポイントを表す2つの Point オブジェクト。
  • scalar -円の色を表す Scalar オブジェクト。 (BGR)
  • thickness -線の太さを表す整数。デフォルトでは、厚さの値は1です。

次のプログラムは、画像に線を引き、JavaFXウィンドウを使用して表示する方法を示しています。

import java.awt.image.BufferedImage;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class DrawingLine extends Application {
   Mat matrix = null;

   @Override
   public void start(Stage stage) throws Exception {

     //Capturing the snapshot from the camera
      DrawingLine obj = new DrawingLine();
      WritableImage writableImage = obj.LoadImage();

     //Setting the image view
      ImageView imageView = new ImageView(writableImage);

     //setting the fit height and width of the image view
      imageView.setFitHeight(600);
      imageView.setFitWidth(600);

     //Setting the preserve ratio of the image view
      imageView.setPreserveRatio(true);

     //Creating a Group object
      Group root = new Group(imageView);

     //Creating a scene object
      Scene scene = new Scene(root, 600, 400);

     //Setting title to the Stage
      stage.setTitle("Drawing a line on the image");

     //Adding scene to the stage
      stage.setScene(scene);

     //Displaying the contents of the stage
      stage.show();
   }
   public WritableImage LoadImage() throws Exception {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap8/input.jpg";
      Mat matrix = Imgcodecs.imread(file);

     //Drawing a line
      Imgproc.line (
         matrix,                   //Matrix obj of the image
         new Point(10, 200),       //p1
         new Point(300, 200),      //p2
         new Scalar(0, 0, 255),    //Scalar object for color
         5                         //Thickness of the line
      );
     //Encoding the image
      MatOfByte matOfByte = new MatOfByte();
      Imgcodecs.imencode(".jpg", matrix, matOfByte);

     //Storing the encoded Mat in a byte array
      byte[] byteArray = matOfByte.toArray();

     //Displaying the image
      InputStream in = new ByteArrayInputStream(byteArray);
      BufferedImage bufImage = ImageIO.read(in);

      this.matrix = matrix;

     //Creating the Writable Image
      WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);
      return writableImage;
   }
   public static void main(String args[]) {
      launch(args);
   }
}

上記のプログラムを実行すると、次の出力が得られます-

線の描画

OpenCV-四角形の描画

*imgproc* クラスの* rectangle()*メソッドを使用して、画像上に長方形を描画できます。 以下は、このメソッドの構文です-
rectangle(img, pt1, pt2, color, thickness)

このメソッドは、次のパラメータを受け入れます-

  • mat -長方形が描かれる画像を表す Mat オブジェクト。
  • pt1およびpt2 -描画される長方形の頂点を表す2つの Point オブジェクト。
  • scalar -長方形の色を表す Scalar オブジェクト。 (BGR)
  • thickness -長方形の厚さを表す整数。デフォルトでは、厚さの値は1です。

次の例は、画像に長方形を描画し、JavaFXウィンドウを使用して表示する方法を示しています。

import java.awt.image.BufferedImage;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class DrawingRectangle extends Application {
   Mat matrix = null;

   @Override
   public void start(Stage stage) throws Exception {
     //Capturing the snapshot from the camera
      DrawingRectangle obj = new DrawingRectangle();
      WritableImage writableImage = obj.LoadImage();

     //Setting the image view
      ImageView imageView = new ImageView(writableImage);

     //setting the fit height and width of the image view
      imageView.setFitHeight(600);
      imageView.setFitWidth(600);

     //Setting the preserve ratio of the image view
      imageView.setPreserveRatio(true);

     //Creating a Group object
      Group root = new Group(imageView);

     //Creating a scene object
      Scene scene = new Scene(root, 600, 400);

     //Setting title to the Stage
      stage.setTitle("Drawing Rectangle on the image");

     //Adding scene to the stage
      stage.setScene(scene);

     //Displaying the contents of the stage
      stage.show();
   }
   public WritableImage LoadImage() throws Exception {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap8/input.jpg";
      Mat matrix = Imgcodecs.imread(file);

     //Drawing a Rectangle
      Imgproc.rectangle (
         matrix,                   //Matrix obj of the image
         new Point(130, 50),       //p1
         new Point(300, 280),      //p2
         new Scalar(0, 0, 255),    //Scalar object for color
         5                         //Thickness of the line
      );

     //Encoding the image
      MatOfByte matOfByte = new MatOfByte();
      Imgcodecs.imencode(".jpg", matrix, matOfByte);

     //Storing the encoded Mat in a byte array
      byte[] byteArray = matOfByte.toArray();

     //Displaying the image
      InputStream in = new ByteArrayInputStream(byteArray);
      BufferedImage bufImage = ImageIO.read(in);

      this.matrix = matrix;

     //Creating the Writable Image
      WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);
      return writableImage;
   }
   public static void main(String args[]) {
      launch(args);
   }
}

上記のプログラムを実行すると、次の出力が得られます-

四角形の描画

OpenCV-楕円の描画

*imgproc* クラスの* rectangle()*メソッドを使用して、画像上に楕円を描画できます。 以下は、このメソッドの構文です-
ellipse(img, box, color, thickness)

このメソッドは、次のパラメータを受け入れます-

  • mat -Rectangleが描画されるイメージを表す Mat オブジェクト。

  • box -RotatedRectオブジェクト(楕円はこの長方形に内接して描画されます。)

  • scalar -Rectangleの色を表す Scalar オブジェクト。 (BGR)

  • thickness -長方形の厚さを表す整数。デフォルトでは、厚さの値は1です。

    *RotatedRect* クラスのコンストラクターは、以下に示すように、クラス *Point* のオブジェクト、クラスSizeのオブジェクト、およびdouble型の変数を受け入れます。
RotatedRect(Point c, Size s, double a)

次のプログラムは、画像上に楕円を描画し、JavaFXウィンドウを使用して表示する方法を示しています。

import java.awt.image.BufferedImage;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Point;
import org.opencv.core.RotatedRect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class DrawingEllipse extends Application {
   Mat matrix = null;

   @Override
   public void start(Stage stage) throws Exception {
     //Capturing the snapshot from the camera
      DrawingEllipse obj = new DrawingEllipse();
      WritableImage writableImage = obj.LoadImage();

     //Setting the image view
      ImageView imageView = new ImageView(writableImage);

     //setting the fit height and width of the image view
      imageView.setFitHeight(600);
      imageView.setFitWidth(600);

     //Setting the preserve ratio of the image view
      imageView.setPreserveRatio(true);

     //Creating a Group object
      Group root = new Group(imageView);

     //Creating a scene object
      Scene scene = new Scene(root, 600, 400);

     //Setting title to the Stage
      stage.setTitle("Drawing Ellipse on the image");

     //Adding scene to the stage
      stage.setScene(scene);

     //Displaying the contents of the stage
      stage.show();
   }
   public WritableImage LoadImage() throws Exception {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap8/input.jpg";
      Mat matrix = Imgcodecs.imread(file);

     //Drawing an Ellipse
      Imgproc.ellipse (
         matrix,                         //Matrix obj of the image
         new RotatedRect (               //RotatedRect(Point c, Size s, double a)
            new Point(200, 150),
            new Size(260, 180), 180
         ),
         new Scalar(0, 0, 255),          //Scalar object for color
         10                              //Thickness of the line
      );

     //Encoding the image
      MatOfByte matOfByte = new MatOfByte();
      Imgcodecs.imencode(".jpg", matrix, matOfByte);

     //Storing the encoded Mat in a byte array
      byte[] byteArray = matOfByte.toArray();

     //Displaying the image
      InputStream in = new ByteArrayInputStream(byteArray);
      BufferedImage bufImage = ImageIO.read(in);

      this.matrix = matrix;

     //Creating the Writable Image
      WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);

      return writableImage;
   }
   public static void main(String args[]) {
      launch(args);
   }
}

上記のプログラムを実行すると、次の出力が得られます-

楕円を描く

OpenCV-ポリラインの描画

*imgproc* クラスの* polylines()*メソッドを使用して、画像にポリラインを描画できます。 このメソッドの構文は次のとおりです。
polylines(img, pts, isClosed, color, thickness)

このメソッドは、次のパラメータを受け入れます-

  • mat -ポリラインが描画される画像を表す Mat オブジェクト。

  • pts -タイプ MatOfPoint のオブジェクトを保持する List オブジェクト。

  • isClosed -ポリラインが閉じている天気を指定するブール型のパラメータ。

  • scalar -ポリラインの色を表す Scalar オブジェクト。 (BGR)

  • thickness -ポリラインの太さを表す整数。デフォルトでは、厚さの値は1です。

    *MatOfPoint* クラスのコンストラクターは、クラス *Point* のオブジェクトを受け入れます。
MatOfPoint(Point... a)

次のプログラムは、イメージにポリラインを描画し、JavaFXウィンドウを使用して表示する方法を示しています。

import java.awt.image.BufferedImage;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class DrawingPolyLines extends Application {
   Mat matrix = null;

   @Override
   public void start(Stage stage) throws Exception {
     //Capturing the snapshot from the camera
      DrawingPolyLines obj = new DrawingPolyLines();
      WritableImage writableImage = obj.LoadImage();

     //Setting the image view
      ImageView imageView = new ImageView(writableImage);

     //setting the fit height and width of the image view
      imageView.setFitHeight(600);
      imageView.setFitWidth(600);

     //Setting the preserve ratio of the image view
      imageView.setPreserveRatio(true);

     //Creating a Group object
      Group root = new Group(imageView);

     //Creating a scene object
      Scene scene = new Scene(root, 600, 400);

     //Setting title to the Stage
      stage.setTitle("Drawing Polylines on the image");

     //Adding scene to the stage
      stage.setScene(scene);

     //Displaying the contents of the stage
      stage.show();
   }
   public WritableImage LoadImage() throws Exception {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap8/input.jpg";
      Mat matrix = Imgcodecs.imread(file);

      List<MatOfPoint> list = new ArrayList();
      list.add(
         new MatOfPoint (
            new Point(75, 100), new Point(350, 100),
            new Point(75, 150), new Point(350, 150),
            new Point(75, 200), new Point(350, 200),
            new Point(75, 250), new Point(350, 250)
         )
      );
     //Drawing polylines
      Imgproc.polylines (
         matrix,                   //Matrix obj of the image
         list,                     //java.util.List<MatOfPoint> pts
         false,                    //isClosed
         new Scalar(0, 0, 255),    //Scalar object for color
         2                         //Thickness of the line
      );
     //Encoding the image
      MatOfByte matOfByte = new MatOfByte();
      Imgcodecs.imencode(".jpg", matrix, matOfByte);

     //Storing the encoded Mat in a byte array
      byte[] byteArray = matOfByte.toArray();

     //Displaying the image
      InputStream in = new ByteArrayInputStream(byteArray);
      BufferedImage bufImage = ImageIO.read(in);

      this.matrix = matrix;

     //Creating the Writable Image
      WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);
      return writableImage;
   }
   public static void main(String args[]) {
      launch(args);
   }
}

上記のプログラムを実行すると、次の出力が得られます-

ポリラインの描画

OpenCV-凸ポリラインの描画

*imgproc* クラスの* fillconvexPoly()*メソッドを使用して、画像上に凸ポリラインを描画できます。 このメソッドの構文は次のとおりです。
fillConvexPoly(Mat img, MatOfPoint points, Scalar color)

このメソッドは、次のパラメータを受け入れます-

  • mat -凸面のポリラインが描画される画像を表す Mat オブジェクト。

  • points -凸ポリラインが描画されるポイントを表す MatOfPoint オブジェクト。

  • scalar -凸ポリラインの色を表す Scalar オブジェクト。 (BGR)

    *MatOfPoint* クラスのコンストラクターは、クラス *Point* のオブジェクトを受け入れます。
MatOfPoint(Point... a)

次のプログラムは、画像上に凸ポリラインを描画し、JavaFXウィンドウを使用して表示する方法を示しています。

import java.awt.image.BufferedImage;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class FillConvexPoly extends Application {
   Mat matrix = null;

   @Override
   public void start(Stage stage) throws Exception {
     //Capturing the snapshot from the camera
      FillConvexPoly obj = new FillConvexPoly();
      WritableImage writableImage = obj.LoadImage();

     //Setting the image view
      ImageView imageView = new ImageView(writableImage);

     //setting the fit height and width of the image view
      imageView.setFitHeight(600);
      imageView.setFitWidth(600);

     //Setting the preserve ratio of the image view
      imageView.setPreserveRatio(true);

     //Creating a Group object
      Group root = new Group(imageView);

     //Creating a scene object
      Scene scene = new Scene(root, 600, 400);

     //Setting title to the Stage
      stage.setTitle("Drawing convex Polylines (fill) on the image");

     //Adding scene to the stage
      stage.setScene(scene);

     //Displaying the contents of the stage
      stage.show();
   }
   public WritableImage LoadImage() throws Exception {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap8/input.jpg";
      Mat matrix = Imgcodecs.imread(file);

      MatOfPoint matOfPoint = new MatOfPoint (
         new Point(75, 100), new Point(350, 100),
         new Point(75, 150), new Point(350, 150),
         new Point(75, 200), new Point(350, 200),
         new Point(75, 250), new Point(350, 250)
      );
     //Drawing polylines
      Imgproc.fillConvexPoly (
         matrix,                      //Matrix obj of the image
         matOfPoint,                  //java.util.List<MatOfPoint> pts
         new Scalar(0, 0, 255)        //Scalar object for color
      );
     //Encoding the image
      MatOfByte matOfByte = new MatOfByte();
      Imgcodecs.imencode(".jpg", matrix, matOfByte);

     //Storing the encoded Mat in a byte array
      byte[] byteArray = matOfByte.toArray();

     //Displaying the image
      InputStream in = new ByteArrayInputStream(byteArray);
      BufferedImage bufImage = ImageIO.read(in);
      this.matrix = matrix;

     //Creating the Writable Image
      WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);
      return writableImage;
   }
   public static void main(String args[]) {
      launch(args);
   }
}

上記のプログラムを実行すると、次の出力が得られます-

凸面ポリラインの描画

OpenCV-矢印付きの線の描画

*imgproc* クラスの* arrowedLine()*メソッドを使用して、画像に矢印付きの線を描画できます。 以下は、このメソッドの構文です-
arrowedLine(Mat img, Point pt1, Point pt2, Scalar color)

このメソッドは、次のパラメータを受け入れます-

  • mat -矢印付きの線が描画される画像を表す Mat オブジェクト。
  • pt1およびpt2 -矢印の付いた線が描画されるポイントを表す2つの Point オブジェクト。
  • scalar -矢印付きの線の色を表す Scalar オブジェクト。 (BGR)

次のプログラムは、画像に矢印付きの線を描画し、JavaFXウィンドウを使用して表示する方法を示しています。

import java.awt.image.BufferedImage;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class DrawingArrowedLine extends Application {
   Mat matrix = null;

   @Override
   public void start(Stage stage) throws Exception {
     //Capturing the snapshot from the camera
      DrawingArrowedLine obj = new DrawingArrowedLine();
      WritableImage writableImage = obj.LoadImage();

     //Setting the image view
      ImageView imageView = new ImageView(writableImage);

     //setting the fit height and width of the image view
      imageView.setFitHeight(600);
      imageView.setFitWidth(600);

     //Setting the preserve ratio of the image view
      imageView.setPreserveRatio(true);

     //Creating a Group object
      Group root = new Group(imageView);

     //Creating a scene object
      Scene scene = new Scene(root, 600, 400);

     //Setting title to the Stage
      stage.setTitle("Drawing a line on the image");

     //Adding scene to the stage
      stage.setScene(scene);

     //Displaying the contents of the stage
      stage.show();
   }
   public WritableImage LoadImage() throws Exception {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="C:/EXAMPLES/OpenCV/Aish.jpg";
      Mat matrix = Imgcodecs.imread(file);

     //Drawing a line
      Imgproc.arrowedLine(
         matrix,                      //Matrix obj of the image
         new Point(10, 200),          //p1
         new Point(590, 200),         //p2
         new Scalar(0, 100, 255)      //Scalar object for color
      );

     //arrowedLine(Mat img, Point pt1, Point pt2, Scalar color)
     //Encoding the image
      MatOfByte matOfByte = new MatOfByte();
      Imgcodecs.imencode(".jpg", matrix, matOfByte);

     //Storing the encoded Mat in a byte array
      byte[] byteArray = matOfByte.toArray();

     //Displaying the image
      InputStream in = new ByteArrayInputStream(byteArray);
      BufferedImage bufImage = ImageIO.read(in);
      this.matrix = matrix;

     //Creating the Writable Image
      WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);

      return writableImage;
   }
   public static void main(String args[]) {
      launch(args);
   }
}

上記のプログラムを実行すると、次の出力が得られます-

矢印付きの線の描画

OpenCV-テキストの追加

*imgproc* クラスの* arrowedLine()*メソッドを使用して、画像にテキストを追加できます。 このメソッドの構文は次のとおりです。
putText(img, text, org, fontFace, fontScale, Scalar color, int thickness)

このメソッドは、次のパラメータを受け入れます-

  • mat -テキストが追加される画像を表す Mat オブジェクト。
  • text -追加されるテキストを表す string 変数。
  • org -画像の左下隅のテキスト文字列を表す Point オブジェクト。
  • fontFace -フォントの種類を表す整数型の変数。
  • fontScale -フォント固有の基本サイズを乗算したスケール係数を表すdouble型の変数。
  • scalar -追加されるテキストの色を表す Scalar オブジェクト。 (BGR)
  • thickness -デフォルトで線の太さを表す整数、太さの値は1です。

次のプログラムは、画像にテキストを追加し、JavaFXウィンドウを使用して表示する方法を示しています。

import java.awt.image.BufferedImage;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class AddingTextToImage extends Application {
   Mat matrix = null;

   @Override
   public void start(Stage stage) throws Exception {
     //Capturing the snapshot from the camera
      AddingTextToImage obj = new AddingTextToImage();
      WritableImage writableImage = obj.LoadImage();

     //Setting the image view
      ImageView imageView = new ImageView(writableImage);

     //setting the fit height and width of the image view
      imageView.setFitHeight(600);
      imageView.setFitWidth(600);

     //Setting the preserve ratio of the image view
      imageView.setPreserveRatio(true);

     //Creating a Group object
      Group root = new Group(imageView);

     //Creating a scene object
      Scene scene = new Scene(root, 600, 400);

     //Setting title to the Stage
      stage.setTitle("Adding text to an image");

     //Adding scene to the stage
      stage.setScene(scene);

     //Displaying the contents of the stage
      stage.show();
   }
   public WritableImage LoadImage() throws Exception {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap8/input.jpg";
      Mat matrix = Imgcodecs.imread(file);

     //Adding Text
      Imgproc.putText (
         matrix,                         //Matrix obj of the image
         "Ravivarma's Painting",         //Text to be added
         new Point(10, 50),              //point
         Core.FONT_HERSHEY_SIMPLEX ,     //front face
         1,                              //front scale
         new Scalar(0, 0, 0),            //Scalar object for color
         4                               //Thickness
      );

     //Encoding the image
      MatOfByte matOfByte = new MatOfByte();
      Imgcodecs.imencode(".jpg", matrix, matOfByte);

     //Storing the encoded Mat in a byte array
      byte[] byteArray = matOfByte.toArray();

     //Displaying the image
      InputStream in = new ByteArrayInputStream(byteArray);
      BufferedImage bufImage = ImageIO.read(in);
      this.matrix = matrix;

     //Creating the Writable Image
      WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);
      return writableImage;
   }
   public static void main(String args[]) {
      launch(args);
   }
}

上記のプログラムを実行すると、次の出力が得られます-

テキストの追加

OpenCV-ぼかし(平均化)

ぼかし(平滑化)は、画像ノイズを減らすために一般的に使用される画像処理操作です。 このプロセスは、エッジなどの高周波コンテンツを画像から削除し、滑らかにします。

一般に、ぼかしは、ローパスフィルターカーネルを介して画像を畳み込む(画像の各要素がローカルネイバーに追加され、カーネルによって重み付けされます)ことによって実現されます。

ぼかし(平均化)

この操作中、画像はボックスフィルター(正規化)で畳み込まれます。 このプロセスでは、画像の中心要素がカーネル領域内のすべてのピクセルの平均に置き換えられます。

*imgproc* クラスの* blur()*メソッドを使用して、画像に対してこの操作を実行できます。 以下は、このメソッドの構文です-
blur(src, dst, ksize, anchor, borderType)

このメソッドは、次のパラメータを受け入れます-

  • src -この操作のソース(入力画像)を表す Mat オブジェクト。
  • dst -この操作の宛先(出力イメージ)を表す Mat オブジェクト。
  • ksize -カーネルのサイズを表す Size オブジェクト。
  • アンカー-アンカーポイントを表す整数型の変数。
  • borderType -出力に使用される境界線の種類を表す整数型の変数。

次のプログラムは、画像に対して平均化(ぼかし)操作を実行する方法を示しています。

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class BlurTest {
   public static void main(String args[]) {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="C:/EXAMPLES/OpenCV/sample.jpg";
      Mat src = Imgcodecs.imread(file);

     //Creating an empty matrix to store the result
      Mat dst = new Mat();

     //Creating the Size and Point objects
      Size size = new Size(45, 45);
      Point point = new Point(20, 30);

     //Applying Blur effect on the Image
      Imgproc.blur(src, dst, size, point, Core.BORDER_DEFAULT);

     //blur(Mat src, Mat dst, Size ksize, Point anchor, int borderType)
     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap9/blur.jpg", dst);
      System.out.println("Image processed");
   }
}

上記のプログラムで指定された入力画像 sample.jpg が次のものであると仮定します。

サンプル画像

出力

プログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

ぼかし(平均化)

OpenCV-ガウスぼかし

ガウスぼかし操作では、画像はボックスフィルターではなくガウスフィルターで畳み込まれます。 ガウスフィルターは、高周波成分を除去するローパスフィルターです。

*imgproc* クラスの* Gaussianblur()*メソッドを使用して、画像に対してこの操作を実行できます。 以下は、このメソッドの構文です-
GaussianBlur(src, dst, ksize, sigmaX)

このメソッドは、次のパラメータを受け入れます-

  • src -この操作のソース(入力画像)を表す Mat オブジェクト。
  • dst -この操作の宛先(出力イメージ)を表す Mat オブジェクト。
  • ksize -カーネルのサイズを表す Size オブジェクト。
  • sigmaX -X方向のガウスカーネル標準偏差を表すdouble型の変数。

次のプログラムは、画像に対してガウスぼかし操作を実行する方法を示しています。

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

public class GaussianTest {
   public static void main(String args[]) {
     //Loading the OpenCV core library
      System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="C:/EXAMPLES/OpenCV/sample.jpg";
      Mat src = Imgcodecs.imread(file);

     //Creating an empty matrix to store the result
      Mat dst = new Mat();

     //Applying GaussianBlur on the Image
      Imgproc.GaussianBlur(src, dst, new Size(45, 45), 0);

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap9/Gaussian.jpg", dst);
      System.out.println("Image Processed");
   }
}

上記のプログラムで指定された入力画像 sample.jpg が次のものであると仮定します。

サンプル画像

出力

プログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

ガウスぼかし

OpenCV-中央値ぼかし

中央値ぼかし操作は、他の平均化方法に似ています。 ここでは、画像の中心要素がカーネル領域のすべてのピクセルの中央値に置き換えられます。 この操作は、ノイズを除去しながらエッジを処理します。

*imgproc* クラスの* medianBlur()*メソッドを使用して、画像に対してこの操作を実行できます。 以下は、このメソッドの構文です-
medianBlur(src, dst, ksize)

このメソッドは、次のパラメータを受け入れます-

  • src -この操作のソース(入力画像)を表す Mat オブジェクト。
  • dst -この操作の宛先(出力イメージ)を表す Mat オブジェクト。
  • ksize -カーネルのサイズを表す Size オブジェクト。

次のプログラムは、画像に対して中央値ぼかし操作を実行する方法を示しています。

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

public class MedianBlurTest {
   public static void main(String args[]) {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="C:/EXAMPLES/OpenCV/sample.jpg";
      Mat src = Imgcodecs.imread(file);

     //Creating an empty matrix to store the result
      Mat dst = new Mat();

     //Applying MedianBlur on the Image
      Imgproc.medianBlur(src, dst, 15);

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap9/median.jpg", dst);

      System.out.println("Image Processed");
   }
}

上記のプログラムで指定された入力画像 sample.jpg が次のものであると仮定します。

サンプル画像

出力

プログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

中央値ぼかし

OpenCV-バイラテラルフィルター

画像フィルタリングを使用すると、画像にさまざまな効果を適用できます。 この章と後続の3つの章では、バイラテラルフィルター、ボックスフィルター、SQRボックスフィルター、Filter2Dなどのさまざまなフィルター操作について説明します。

バイラテラルフィルター

バイラテラルフィルター操作は、バイラテラルイメージをフィルターに適用します。 imgproc クラスの* medianBlur()*メソッドを使用して、画像に対してこの操作を実行できます。 このメソッドの構文は次のとおりです。

bilateralFilter(src, dst, d, sigmaColor, sigmaSpace, borderType)

このメソッドは、次のパラメータを受け入れます-

  • src -この操作のソース(入力画像)を表す Mat オブジェクト。
  • dst -この操作の宛先(出力イメージ)を表す Mat オブジェクト。
  • d -ピクセル近傍の直径を表す整数型の変数。
  • sigmaColor -色空間でフィルターシグマを表す整数型の変数。
  • sigmaSpace -座標空間でフィルターシグマを表す整数型の変数。
  • borderType -使用される境界線のタイプを表す整数オブジェクト。

次のプログラムは、画像に対してBilateral Filter操作を実行する方法を示しています。

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

public class BilateralFilter {
   public static void main(String args[]) {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap11/filter_input.jpg";
      Mat src = Imgcodecs.imread(file);

     //Creating an empty matrix to store the result
      Mat dst = new Mat();

     //Applying Bilateral filter on the Image
      Imgproc.bilateralFilter(src, dst, 15, 80, 80, Core.BORDER_DEFAULT);

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap11/bilateralfilter.jpg", dst);

      System.out.println("Image Processed");
   }
}

上記のプログラムで指定された入力画像 filter_input.jpg が次のようになっていると仮定します。

フィルター入力

出力

プログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

双方向フィルター出力

OpenCV-ボックスフィルター

ボックスフィルター操作は、平均化ぼかし操作に似ています。両側画像をフィルターに適用します。 ここで、ボックスを正規化するかどうかを選択できます。

*imgproc* クラスの* boxFilter()*メソッドを使用して、画像に対してこの操作を実行できます。 以下は、このメソッドの構文です-
boxFilter(src, dst, ddepth, ksize, anchor, normalize, borderType)

このメソッドは、次のパラメータを受け入れます-

  • src -この操作のソース(入力画像)を表す Mat オブジェクト。
  • dst -この操作の宛先(出力イメージ)を表す Mat オブジェクト。
  • ddepth -出力画像の深さを表す整数型の変数。
  • ksize -ぼかしカーネルのサイズを表す Size オブジェクト。
  • アンカー-アンカーポイントを表す整数型の変数。
  • Normalize -カーネルを正規化する天気を指定するブール型の変数。
  • borderType -使用される境界線のタイプを表す整数オブジェクト。

次のプログラムは、画像に対してボックスフィルター操作を実行する方法を示しています。

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class BoxFilterTest {
   public static void main( String[] args ) {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file = "E:/OpenCV/chap11/filter_input.jpg";
      Mat src = Imgcodecs.imread(file);

     //Creating an empty matrix to store the result
      Mat dst = new Mat();

     //Creating the objects for Size and Point
      Size size = new Size(45, 45);
      Point point = Point(-1, -1);

     //Applying Box Filter effect on the Image
      Imgproc.boxFilter(src, dst, 50, size, point, true, Core.BORDER_DEFAULT);

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap11/boxfilterjpg", dst);

      System.out.println("Image Processed");
   }
}

上記のプログラムで指定された入力画像 filter_input.jpg が次のようになっていると仮定します。

フィルター入力

出力

プログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

ボックスフィルター

OpenCV-SQRBoxフィルター

*imgproc* クラスの* boxFilter()*メソッドを使用して、画像に対してSQRBoxフィルター操作を実行できます。 以下は、このメソッドの構文です-
sqrBoxFilter(src, dst, ddepth, ksize)

このメソッドは、次のパラメータを受け入れます-

  • src -この操作のソース(入力画像)を表す Mat オブジェクト。
  • dst -この操作の宛先(出力イメージ)を表す Mat オブジェクト。
  • ddepth -出力画像の深さを表す整数型の変数。
  • ksize -ぼかしカーネルのサイズを表す Size オブジェクト。

次のプログラムは、特定の画像でSqrboxフィルター操作を実行する方法を示しています。

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

public class SqrBoxFilterTest {
   public static void main( String[] args ) {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap11/filter_input.jpg";
      Mat src = Imgcodecs.imread(file);

     //Creating an empty matrix to store the result
      Mat dst = new Mat();

     //Applying Box Filter effect on the Image
      Imgproc.sqrBoxFilter(src, dst, -1, new Size(1, 1));

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap11/sqrboxfilter.jpg", dst);

      System.out.println("Image Processed");
   }
}

上記のプログラムで指定された入力画像 filter_input.jpg が次のようになっていると仮定します。

フィルター入力

出力

プログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

SQRBox Filter

OpenCV-Filter2D

Filter2D操作は、カーネルとイメージを畳み込みます。 imgproc クラスの* Filter2D()*メソッドを使用して、画像に対してこの操作を実行できます。 以下は、このメソッドの構文です-

filter2D(src, dst, ddepth, kernel)

このメソッドは、次のパラメータを受け入れます-

  • src -この操作のソース(入力画像)を表す Mat オブジェクト。
  • dst -この操作の宛先(出力イメージ)を表す Mat オブジェクト。
  • ddepth -出力画像の深さを表す整数型の変数。
  • kernel -畳み込みカーネルを表す Mat オブジェクト。

次のプログラムは、画像に対してFilter2D操作を実行する方法を示しています。

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

public class Filter2D {
   public static void main( String[] args ) {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap11/filter_input.jpg";
      Mat src = Imgcodecs.imread(file);

     //Creating an empty matrix to store the result
      Mat dst = new Mat();

     //Creating kernel matrix
      Mat kernel = Mat.ones(2,2, CvType.CV_32F);

      for(int i = 0; i<kernel.rows(); i++) {
         for(int j = 0; j<kernel.cols(); j++) {
            double[] m = kernel.get(i, j);

            for(int k = 1; k<m.length; k++) {
               m[k] = m[k]/(2 * 2);
            }
            kernel.put(i,j, m);
         }
      }
      Imgproc.filter2D(src, dst, -1, kernel);
      Imgcodecs.imwrite("E:/OpenCV/chap11/filter2d.jpg", dst);
      System.out.println("Image Processed");
   }
}

上記のプログラムで指定された入力画像 filter_input.jpg が次のようになっていると仮定します。

フィルター入力

出力

プログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

Filter2D

OpenCV-拡張

侵食と膨張は、2種類の形態学的操作です。 名前が示すように、形態学的操作は、形状に従って画像を処理する操作のセットです。

与えられた入力画像に基づいて、「構造要素」が開発されます。 これは、2つの手順のいずれでも実行できます。 これらは、ノイズを除去して欠陥を解決し、画像を鮮明にすることを目的としています。

膨張

この手順は、正方形や円などの特定の形状のカーネルによる畳み込みに従います。 このカーネルには、その中心を示すアンカーポイントがあります。

このカーネルは、最大ピクセル値を計算するために画像に重ねられます。 計算後、画像は中央のアンカーに置き換えられます。 この手順を使用すると、明るい領域の領域のサイズが大きくなるため、画像サイズが大きくなります。

たとえば、白い色合いまたは明るい色合いのオブジェクトのサイズは増加し、黒い色合いまたは暗い色合いのオブジェクトのサイズは減少します。

*imgproc* クラスの* dilate()*メソッドを使用して、画像に対して膨張操作を実行できます。 このメソッドの構文は次のとおりです。
dilate(src, dst, kernel)

このメソッドは、次のパラメータを受け入れます-

  • src -この操作のソース(入力画像)を表す Mat オブジェクト。
  • dst -この操作の宛先(出力イメージ)を表す Mat オブジェクト。
  • kernel -カーネルを表す Mat オブジェクト。

  • getStructuringElement()メソッドを使用して、カーネルマトリックスを準備できます。 このメソッドは、 *morph_rect タイプと Size タイプのオブジェクトを表す整数を受け入れます。
Imgproc.getStructuringElement(int shape, Size ksize);

次のプログラムは、特定の画像に対して膨張操作を実行する方法を示しています。

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

public class DilateTest {
   public static void main( String[] args ) {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="C:/EXAMPLES/OpenCV/sample.jpg";
      Mat src = Imgcodecs.imread(file);

     //Creating an empty matrix to store the result
      Mat dst = new Mat();

     //Preparing the kernel matrix object
      Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT,
         new  Size((2*2) + 1, (2*2)+1));

     //Applying dilate on the Image
      Imgproc.dilate(src, dst, kernel);

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap10/Dilation.jpg", dst);

      System.out.println("Image Processed");
   }
}

入力

上記のプログラムで指定された入力画像 sample.jpg が次のものであると仮定します。

サンプル画像

出力

プログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

膨張

OpenCV-侵食

侵食は、膨張と非常によく似たプロセスです。 ただし、ここで計算されるピクセル値は、膨張の最大値ではなく最小値です。 画像はアンカーポイントの下でその最小ピクセル値に置き換えられます。

この手順では、暗い領域のサイズが大きくなり、明るい領域が減少します。 たとえば、暗い色合いまたは黒い色合いのオブジェクトのサイズは大きくなりますが、白い色合いまたは明るい色合いのオブジェクトは小さくなります。

*imgproc* クラスの* erode()*メソッドを使用して、画像に対してこの操作を実行できます。 以下は、このメソッドの構文です-
erode(src, dst, kernel)

このメソッドは、次のパラメータを受け入れます-

  • src -この操作のソース(入力画像)を表す Mat オブジェクト。
  • dst -この操作の宛先(出力イメージ)を表す Mat オブジェクト。
  • kernel -カーネルを表す Mat オブジェクト。
  • getStructuringElement()メソッドを使用して、カーネルマトリックスを準備できます。 このメソッドは、 *morph_rect タイプと Size タイプのオブジェクトを表す整数を受け入れます。
Imgproc.getStructuringElement(int shape, Size ksize);

次のプログラムは、指定されたイメージで収縮操作を実行する方法を示しています。

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

public class ErodeTest {
   public static void main( String[] args ) {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="C:/EXAMPLES/OpenCV/sample.jpg";
      Mat src = Imgcodecs.imread(file);

     //Creating an empty matrix to store the result
      Mat dst = new Mat();

     //Preparing the kernel matrix object
      Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT,
         new  Size((2*2) + 1, (2*2)+1));

     //Applying erode on the Image
      Imgproc.erode(src, dst, kernel);

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap10/Erosion.jpg", dst);

      System.out.println("Image processed");
   }
}

上記のプログラムで指定された入力画像 sample.jpg が次のものであると仮定します。

サンプル画像

出力

プログラムを実行すると、次の出力が得られます-

Image Loaded

指定したパスを開くと、次のように出力画像を観察できます-

侵食

OpenCV-モルフォロジー操作

前の章で、侵食*と*膨張*のプロセスについて説明しました。 これら2つに加えて、OpenCVにはより多くの形態変換があります。 クラス *Imgproc のメソッドの* morphologyEx()*は、特定の画像でこれらの操作を実行するために使用されます。

以下は、このメソッドの構文です-

morphologyEx(src, dst, op, kernel)

このメソッドは、次のパラメータを受け入れます-

  • src -ソース(入力)画像を表すクラス Mat のオブジェクト。
  • dst -宛先(出力)イメージを表すクラス Mat のオブジェクト。
  • op -形態学的操作のタイプを表す整数。
  • kernel -カーネル行列。

次のプログラムは、OpenCVライブラリを使用して画像にモルフォロジー演算 "top-hat" を適用する方法を示しています。

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

public class MorphologyExTest {
   public static void main(String args[]) {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap12/morph_input.jpg";
      Mat src = Imgcodecs.imread(file);

     //Creating an empty matrix to store the result
      Mat dst = new Mat();

     //Creating kernel matrix
      Mat kernel = Mat.ones(5,5, CvType.CV_32F);

     //Applying Blur effect on the Image
      Imgproc.morphologyEx(src, dst, Imgproc.MORPH_TOPHAT, kernel);

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap12/morph_tophat.jpg", dst);

      System.out.println("Image Processed");
   }
}

上記のプログラムで指定された入力画像 morph_input.jpg が次のように仮定します。

モーフ入力

出力

プログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

モーフ出力

その他の操作

OpenCVは、前の*例*で示した形態学的操作 TOPHAT に加えて、他のさまざまな種類の形態に対応しています。 これらのタイプはすべて、 Imgproc クラスの事前定義された静的フィールド(固定値)で表されます。

それぞれの事前定義された値を* morphologyEx()メソッドのパラメーター *op に渡すことで、必要な形態のタイプを選択できます。

//Applying Blur effect on the Image
Imgproc.morphologyEx(src, dst, Imgproc.MORPH_TOPHAT, kernel);

モルフォロジー演算のタイプとそれぞれの出力を表す値は次のとおりです。

Operation and Description Output
MORPH_BLACKHAT MORPH_BLACKHAT
MORPH_CLOSE MORPH_CLOSE
MORPH_CROSS MORPH_CROSS
MORPH_DILATE MORPH_DILATE
MORPH_ELLIPSE MORPH_ELLIPSE
MORPH_ERODE MORPH_ERODE
MORPH_GRADIENT MORPH_GRADIENT
MORPH_OPEN MORPH_OPEN
MORPH_RECT MORPH_RECT
MORPH_TOPHAT MORPH_TOPHAT

OpenCV-画像ピラミッド

ピラミッドは、画像に対する操作です。ここで、

  • 入力画像は、最初に特定の平滑化フィルター(例:ガウス、ラプラシアン)を使用して平滑化され、その後平滑化された画像がサブサンプリングされます。 *このプロセスは複数回繰り返されます。

ピラミッド操作中、画像の滑らかさが増し、解像度(サイズ)が低下します。

ピラミッドアップ

Pyramid Upでは、画像は最初にアップサンプリングされ、その後ぼやけます。* imgproc クラスの pyrUP()*メソッドを使用して、画像に対してピラミッドアップ操作を実行できます。 以下は、このメソッドの構文です-

pyrUp(src, dst, dstsize, borderType)

このメソッドは、次のパラメータを受け入れます-

  • src -ソース(入力)画像を表すクラス Mat のオブジェクト。
  • mat -宛先(出力)イメージを表すクラス Mat のオブジェクト。
  • サイズ-画像を拡大または縮小するサイズを表す*サイズ*クラスのオブジェクト。
  • borderType -使用される境界線のタイプを表す整数タイプの変数。

次のプログラムは、画像に対してピラミッドアップ操作を実行する方法を示しています。

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

public class PyramidUp {
   public static void main( String[] args ) {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap13/pyramid_input.jpg";
      Mat src = Imgcodecs.imread(file);

     //Creating an empty matrix to store the result
      Mat dst = new Mat();

     //Applying pyrUp on the Image
      Imgproc.pyrUp(src, dst, new Size(src.cols()*2,  src.rows()*2), Core.BORDER_DEFAULT);

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap13/pyrUp_output.jpg", dst);

      System.out.println("Image Processed");
   }
}

上記のプログラムで指定された入力画像 pyramid_input.jpg が次のものであると仮定します。

ピラミッド入力

出力

プログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

ピラミッドアップ出力

ピラミッドダウン

ピラミッドダウンでは、画像は最初にぼやけてからダウンサンプリングされます。 imgproc クラスの* pyrDown()*メソッドを使用して、画像に対してピラミッドダウン操作を実行できます。 以下は、このメソッドの構文です-

pyrDown(src, dst, dstsize, borderType)

このメソッドは、次のパラメータを受け入れます-

  • src -ソース(入力)画像を表すクラス Mat のオブジェクト。
  • mat -宛先(出力)イメージを表すクラス Mat のオブジェクト。
  • サイズ-画像を拡大または縮小するサイズを表す*サイズ*クラスのオブジェクト。
  • borderType -使用される境界線のタイプを表す整数タイプの変数。

次のプログラムは、画像に対してピラミッドダウン操作を実行する方法を示しています。

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

public class PyramidDown {
   public static void main( String[] args ) {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap13/pyramid_input.jpg";
      Mat src = Imgcodecs.imread(file);

     //Creating an empty matrix to store the result
      Mat dst = new Mat();

     //Applying pyrDown on the Image
      Imgproc.pyrDown(src, dst, new Size(src.cols()/2,  src.rows()/2),
         Core.BORDER_DEFAULT);

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap13/pyrDown_output.jpg", dst);

      System.out.println("Image Processed");
   }
}

上記のプログラムで指定された入力画像 pyramid_input.jpg が次のものであると仮定します。

ピラミッド入力

出力

プログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

ピラミッドダウン出力

平均シフトフィルタリング

平均シフトピラミッド操作では、画像の平均シフトセグメンテーションの最初のステップが実行されます。

*imgproc* クラスの* pyrDown()*メソッドを使用して、画像に対してピラミッド平均シフトフィルター操作を実行できます。 このメソッドの構文は次のとおりです。
pyrMeanShiftFiltering(src, dst, sp, sr)

このメソッドは、次のパラメータを受け入れます-

  • src -ソース(入力)画像を表すクラス Mat のオブジェクト。
  • mat -宛先(出力)イメージを表すクラス Mat のオブジェクト。
  • sp -空間ウィンドウ半径を表すdouble型の変数。
  • sr -カラーウィンドウの半径を表すdouble型の変数。

次のプログラムは、特定の画像に対して平均シフトフィルタリング操作を実行する方法を示しています。

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

public class PyramidMeanShift {
   public static void main( String[] args ) {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap13/pyramid_input.jpg";
      Mat src = Imgcodecs.imread(file);

     //Creating an empty matrix to store the result
      Mat dst = new Mat();

     //Applying meanShifting on the Image
      Imgproc.pyrMeanShiftFiltering(src, dst, 200, 300);

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap13/meanShift_output.jpg", dst);

      System.out.println("Image Processed");
   }
}

上記のプログラムで指定された入力画像 pyramid_input.jpg が次のものであると仮定します。

ピラミッド入力

出力

プログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

平均シフトフィルタリング出力

OpenCV-単純なしきい値

しきい値処理は、画像のセグメンテーションの方法であり、一般に、バイナリ画像の作成に使用されます。 しきい値処理には、単純なしきい値処理と適応しきい値処理の2種類があります。

単純なしきい値処理

単純なしきい値操作では、指定されたしきい値より大きい値を持つピクセルに標準値が割り当てられます。

  • Imgprocクラス*のメソッド* threshold()*を使用して、画像に対して簡単なしきい値操作を実行できます。このメソッドの構文は次のとおりです。
threshold(src, dst, thresh, maxval, type)

このメソッドは、次のパラメータを受け入れます-

  • src -ソース(入力)画像を表すクラス Mat のオブジェクト。
  • dst -宛先(出力)イメージを表すクラス Mat のオブジェクト。
  • thresh -しきい値を表すdouble型の変数。
  • maxval -ピクセル値がしきい値よりも大きい場合に与えられる値を表すdouble型の変数。
  • type -使用されるしきい値のタイプを表す整数タイプの変数。

次のプログラムは、OpenCVの画像で単純なしきい値処理を実行する方法を示しています。

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

public class Thresh {
   public static void main(String args[]) {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap14/thresh_input.jpg";
      Mat src = Imgcodecs.imread(file);

     //Creating an empty matrix to store the result
      Mat dst = new Mat();
      Imgproc.threshold(src, dst, 50, 255, Imgproc.THRESH_BINARY);

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap14/thresh_trunc.jpg", dst);

      System.out.println("Image Processed");
   }
}

上記のプログラムで指定された入力画像 thresh_input.jpg が次のものであると仮定します。

Thresh Input

出力

プログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

Thresh Output

他のタイプの単純なしきい値処理

前の例で示した THRESH_BINARY 操作に加えて、OpenCVはさまざまな種類のしきい値操作に対応しています。 これらのタイプはすべて、 Imgproc クラスの事前定義された静的フィールド(固定値)で表されます。

それぞれの事前定義値を* threshold()メソッドの *type という名前のパラメーターに渡すことで、必要なしきい値操作のタイプを選択できます。

Imgproc.threshold(src, dst, 50, 255, Imgproc.THRESH_BINARY);

以下は、さまざまなタイプのしきい値操作とそれぞれの出力を表す値です。

Operation and Description Output
THRESH_BINARY THRESH_BINARY
THRESH_BINARY_INV THRESH_BINARY_INV
THRESH_TRUNC THRESH_TRUNC
THRESH_TOZERO THRESH_TOZERO
THRESH_TOZERO_INV THRESH_TOZERO_INV

OpenCV-適応しきい値

  • 単純なしきい値*では、しきい値はグローバルです。つまり、画像内のすべてのピクセルで同じです。 *適応型しきい値*は、より小さい領域に対してしきい値が計算される方法であるため、領域ごとに異なるしきい値があります。

OpenCVでは、 Imgproc クラスの* adaptiveThreshold()*メソッドを使用して、画像に対して適応しきい値操作を実行できます。 このメソッドの構文は次のとおりです。

adaptiveThreshold(src, dst, maxValue, adaptiveMethod, thresholdType, blockSize, C)

このメソッドは、次のパラメータを受け入れます-

  • src -ソース(入力)画像を表すクラス Mat のオブジェクト。

  • dst -宛先(出力)イメージを表すクラス Mat のオブジェクト。

  • maxValue -ピクセル値がしきい値よりも大きい場合に与えられる値を表すdouble型の変数。

  • adaptiveMethod -使用される適応方法を表すタイプの整数の変数。 これは、次の2つの値のいずれかになります

  • ADAPTIVE_THRESH_MEAN_C -しきい値は近隣地域の平均です。

  • ADAPTIVE_THRESH_GAUSSIAN_C -しきい値は、重みがガウスウィンドウである近傍値の重み付き合計です。

    *thresholdType* -使用されるしきい値の種類を表す整数型の変数。
    *blockSize* -しきい値の計算に使用されるピクセル近傍のサイズを表す整数型の変数。
    *C* -両方の方法で使用される定数を表すdouble型の変数(平均または加重平均から減算)。

次のプログラムは、OpenCVの画像で適応しきい値操作を実行する方法を示しています。 ここでは、しきい値メソッドに binary および ADAPTIVE_THRESH_MEAN_C タイプの適応しきい値を選択しています。

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

public class AdaptiveThresh {
   public static void main(String args[]) throws Exception {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap14/thresh_input.jpg";

     //Reading the image
      Mat src = Imgcodecs.imread(file,0);

     //Creating an empty matrix to store the result
      Mat dst = new Mat();

      Imgproc.adaptiveThreshold(src, dst, 125, Imgproc.ADAPTIVE_THRESH_MEAN_C,
         Imgproc.THRESH_BINARY, 11, 12);

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap14/Adaptivemean_thresh_binary.jpg", dst);

      System.out.println("Image Processed");
   }
}

上記のプログラムで指定された入力画像 thresh_input.jpg が次のものであると仮定します。

Thresh Input

出力

プログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

適応しきい値出力

他のタイプの適応しきい値処理

前の例で示したように、適応メソッドとしての ADAPTIVE_THRESH_MEAN_C およびしきい値タイプとしての THRESH_BINARY に加えて、これら2つの値の組み合わせをさらに選択できます。

Imgproc.adaptiveThreshold(src, dst, 125, Imgproc.ADAPTIVE_THRESH_MEAN_C,
   Imgproc.THRESH_BINARY, 11, 12);

以下は、パラメータ adaptiveMethod および thresholdType の値のさまざまな組み合わせを表す値と、それぞれの出力です。

adaptiveMethod/thresholdType ADAPTIVE_THRESH_MEAN_C ADAPTIVE_THRESH_GAUSSIAN_C:
THRESH_BINARY ADAPTIVE_THRESH_BINARY ADAPTIVE_THRESH_GAUSSIAN_BINARY
THRESH_BINARY_INV ADAPTIVE_THRESH_BINARY_INV ADAPTIVE_THRESH_GAUSSIAN_BINARY_INV

OpenCV-ボーダーの追加

この章では、画像にヒキガエルの境界線を付ける方法を説明します。

copyMakeBorder()メソッド

このメソッドの構文は次のパッケージ* org.opencv.core。に属するCoreという名前のクラスのメソッド copyMakeBorder()*を使用して、画像にさまざまな境界線を追加できます。

copyMakeBorder(src, dst, top, bottom, left, right, borderType)

このメソッドは、次のパラメータを受け入れます-

  • src -ソース(入力)画像を表すクラス Mat のオブジェクト。
  • dst -宛先(出力)イメージを表すクラス Mat のオブジェクト。
  • top -画像の上部の境界線の長さを表す整数型の整数の変数。
  • bottom -画像の下部の境界線の長さを表す整数型の整数の変数。
  • -整数の変数は、画像の左側の境界線の長さを表す整数型です。
  • right -画像の右側の境界線の長さを表す整数型の変数。
  • borderType -使用される境界線のタイプを表す整数型の変数。

次のプログラムは、特定の画像に境界線を追加する方法を示す例です。

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;

public class AddingBorder {
   public static void main( String[] args ) {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap15/input.jpg";
      Mat src = Imgcodecs.imread(file);

     //Creating an empty matrix to store the result
      Mat dst = new Mat();

      Core.copyMakeBorder(src, dst, 20, 20, 20, 20, Core.BORDER_CONSTANT);
      Imgcodecs.imwrite("E:/OpenCV/chap15/border_constant.jpg", dst);

      System.out.println("Image Processed");
   }
}

上記のプログラムで指定された入力画像 thresh_input.jpg が次のものであると仮定します。

Thresh Input

出力

プログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

ボーダー出力の追加

他の種類のボーダー

境界タイプに加えて、前の例で示した BORDER_CONSTANT は、OpenCVがさまざまな他のタイプの境界に対応しています。 これらのタイプはすべて、Coreクラスの事前定義された静的フィールド(固定値)によって表されます。

それぞれの事前定義値を* copyMakeBorder()メソッドの *borderType という名前のパラメーターに渡すことで、必要なしきい値操作のタイプを選択できます。

Core.copyMakeBorder(src, dst, 20, 20, 20, 20, Core.BORDER_CONSTANT);

以下は、さまざまなタイプの境界操作とそれぞれの出力を表す値です。

Operation and Description Output
BORDER_CONSTANT BORDER_CONSTANT
BORDER_ISOLATED BORDER_ISOLATED
BORDER_DEFAULT BORDER_DEFAULT
BORDER_REFLECT BORDER_REFLECT
BORDER_REFLECT_101 BORDER_REFLECT_101
BORDER_REFLECT101 BORDER_REFLECT101
BORDER_REPLICATE BORDER_REPLICATE
BORDER_WRAP BORDER_WRAP

OpenCV-ソーベル演算子

  • sobel操作*を使用すると、水平方向と垂直方向の両方で画像のエッジを検出できます。 メソッド* sobel()*を使用して、画像にsobel操作を適用できます。 以下は、このメソッドの構文です-
Sobel(src, dst, ddepth, dx, dy)

このメソッドは、次のパラメータを受け入れます-

  • src -ソース(入力)画像を表すクラス Mat のオブジェクト。
  • dst -宛先(出力)イメージを表すクラス Mat のオブジェクト。
  • ddepth -画像の深さを表す整数変数(-1)
  • dx -x導関数を表す整数変数。 (0または1)
  • dy -y導関数を表す整数変数。 (0または1)

次のプログラムは、特定の画像でSobel操作を実行する方法を示しています。

import org.opencv.core.Core;
import org.opencv.core.Mat;

import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class SobelTest {
   public static void main(String args[]) {
     //Loading the OpenCV core library
      System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap16/sobel_input.jpg";
      Mat src = Imgcodecs.imread(file);

     //Creating an empty matrix to store the result
      Mat dst = new Mat();

     //Applying sobel on the Image
      Imgproc.Sobel(src, dst, -1, 1, 1);

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap16/sobel_output.jpg", dst);

      System.out.println("Image processed");
   }
}

上記のプログラムで指定された入力画像 sobel_input.jpg が次のものであると仮定します。

ウィンドウ入力

出力

プログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

Sobel Output

ソーベルバリアント

最後に異なる値をパラメータ(dxとdy)(0と1の間)に渡すと、異なる出力が得られます-

//Applying sobel on the Image
Imgproc.Sobel(src, dst, -1, 1, 1);

次の表に、メソッド* Sobel()の変数 *dx および dy のさまざまな値と、それぞれの出力を示します。

X-derivative Y-derivative Output
0 1 Sobel 01
1 0 Sobel 10
1 1 Sobel 11

OpenCV-Scharrオペレーター

Scharrは、水平および垂直方向の画像の2次導関数を検出するためにも使用されます。 メソッド* scharr()*を使用して、画像に対してscharr操作を実行できます。 以下は、このメソッドの構文です-

Scharr(src, dst, ddepth, dx, dy)

このメソッドは、次のパラメータを受け入れます-

  • src -ソース(入力)画像を表すクラス Mat のオブジェクト。
  • dst -宛先(出力)イメージを表すクラス Mat のオブジェクト。
  • ddepth -画像の深さを表す整数変数(-1)
  • dx -x導関数を表す整数変数。 (0または1)
  • dy -y導関数を表す整数変数。 (0または1)

次のプログラムは、特定の画像にscharrを適用する方法を示しています。

import org.opencv.core.Core;
import org.opencv.core.Mat;

import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class ScharrTest {

   public static void main( String[] args ) {

     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap16/sobel_input.jpg";
      Mat src = Imgcodecs.imread(file);

     //Creating an empty matrix to store the result
      Mat dst = new Mat();

     //Applying Box Filter effect on the Image
      Imgproc.Scharr(src, dst, Imgproc.CV_SCHARR, 0, 1);

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap16/scharr_output.jpg", dst);

      System.out.println("Image processed");
   }
}

上記のプログラムで指定された入力画像 scharr_input.jpg が次のものであると仮定します。

ウィンドウ入力

出力

それを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

Scharr Output

より多くのscharr誘導体

最後に異なる値をパラメータ(dxとdy)(0と1の間)に渡すと、異なる出力が得られます-

//Applying scharr on the Image
Imgproc.Scharr(src, dst, -1, 1, 1);

以下は、メソッド* scharr()の変数 *dx および dy のさまざまな値とそれぞれの出力をリストした表です。

X-derivative Y-derivative Output
0 1 Scharr 01
1 0 Scharr 10

OpenCV-ラプラシアン変換

ラプラシアン演算子は、画像内のエッジを見つけるために使用される微分演算子でもあります。 これは二次微分マスクです。 このマスクには、さらに2つの分類があります。1つは正のラプラシアン演算子で、もう1つは負のラプラシアン演算子です。

他の演算子とは異なり、ラプラシアンは特定の方向のエッジを取り出しませんでしたが、次の分類ではエッジを取り出します。

  • 内向きエッジ

  • 外向きエッジ

    *imgproc* クラスの* Laplacian()*メソッドを使用して、画像に対して* Laplacian変換*操作を実行できます。このメソッドの構文は次のとおりです。
Laplacian(src, dst, ddepth)

このメソッドは、次のパラメータを受け入れます-

  • src -この操作のソース(入力画像)を表す Mat オブジェクト。
  • dst -この操作の宛先(出力イメージ)を表す Mat オブジェクト。
  • ddepth -宛先画像の深さを表す整数型の変数。

次のプログラムは、特定の画像に対してラプラス変換操作を実行する方法を示しています。

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

public class LaplacianTest {
   public static void main(String args[]) {
     //Loading the OpenCV core library
      System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap18/laplacian_input.jpg";
      Mat src = Imgcodecs.imread(file);

     //Creating an empty matrix to store the result
      Mat dst = new Mat();

     //Applying GaussianBlur on the Image
      Imgproc.Laplacian(src, dst, 10);

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap18/laplacian.jpg", dst);

      System.out.println("Image Processed");
   }
}

上記のプログラムで指定された入力画像 laplacian_input.jpg が次のものであると仮定します。

ラプラシアン入力

出力

プログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

ラプラシアン出力

OpenCV-距離変換

  • 距離変換*演算子は通常、バイナリイメージを入力として受け取ります。 この操作では、前景領域内のポイントのグレーレベルの強度を変更して、それぞれの距離を最も近い0の値(境界)から離します。

メソッド* distanceTransform()*を使用して、OpenCVで距離変換を適用できます。 このメソッドの構文は次のとおりです。

distanceTransform(src, dst, distanceType, maskSize)

このメソッドは、次のパラメータを受け入れます-

  • src -ソース(入力)画像を表すクラス Mat のオブジェクト。
  • dst -宛先(出力)イメージを表すクラス Mat のオブジェクト。
  • distanceType -適用される距離変換のタイプを表す整数型の変数。
  • maskSize -使用するマスクサイズを表す整数型の変数。

次のプログラムは、特定の画像で距離変換操作を実行する方法を示しています。

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

public class DistanceTransform {
   public static void main(String args[]) {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap19/input.jpg";
      Mat src = Imgcodecs.imread(file,0);

     //Creating an empty matrix to store the results
      Mat dst = new Mat();
      Mat binary = new Mat();

     //Converting the grayscale image to binary image
      Imgproc.threshold(src, binary, 100, 255, Imgproc.THRESH_BINARY);

     //Applying distance transform
      Imgproc.distanceTransform(mat, dst, Imgproc.DIST_C, 3);

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap19/distnceTransform.jpg", dst);

      System.out.println("Image Processed");
   }
}

上記のプログラムで指定された入力画像 input.jpg が次のようになっていると仮定します。

距離変換入力

出力

プログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

距離変換出力

距離変換操作のタイプ

前の例で示した距離操作タイプ DIST_C に加えて、OpenCVは他のさまざまなタイプの距離変換操作に対応しています。 これらのタイプはすべて、Imgprocクラスの事前定義された静的フィールド(固定値)によって表されます。

それぞれの事前定義値を* distanceTransform()メソッドの *distanceType という名前のパラメーターに渡すことで、必要な距離変換操作のタイプを選択できます。

//Applying distance transform
Imgproc.distanceTransform(mat, dst, Imgproc.DIST_C, 3);

以下は、さまざまなタイプの distanceTransform 操作とそれぞれの出力を表す値です。

Operation and Description Output
DIST_C DIST_C
DIST_L1 DIST_L1
DIST_L2 DIST_L2
DIST_LABEL_PIXEL DIST_LABEL_PIXEL
DIST_MASK_3 DIST_MASK_3

OpenCV-カメラの使用

この章では、OpenCVを使用してシステムカメラを使用してフレームをキャプチャする方法を学習します。 org.opencv.videoio パッケージの VideoCapture クラスには、カメラを使用してビデオをキャプチャするクラスとメソッドが含まれています。 ステップバイステップでフレームをキャプチャする方法を学びましょう-

ステップ1:OpenCVネイティブライブラリをロードする

OpenCVライブラリを使用してJavaコードを作成する場合、最初に行う必要があるステップは、* loadLibrary()*を使用してOpenCVのネイティブライブラリをロードすることです。 以下に示すように、OpenCVネイティブライブラリをロードします。

//Loading the core library
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

ステップ2:ビデオキャプチャクラスをインスタンス化する

このチュートリアルで前述した関数のいずれかを使用して、Matクラスをインスタンス化します。

//Instantiating the VideoCapture class (camera:: 0)
VideoCapture capture = new VideoCapture(0);

ステップ3:フレームを読む

*VideoCapture* クラスの* read()*メソッドを使用して、カメラからフレームを読み取ることができます。 このメソッドは、 *Mat* クラスのオブジェクトを受け入れて、読み取ったフレームを保存します。
//Reading the next video frame from the camera
Mat matrix = new Mat();
capture.read(matrix);

次のプログラムは、カメラを使用してフレームをキャプチャし、JavaFXウィンドウを使用して表示する方法を示しています。 また、キャプチャされたフレームを保存します。

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.WritableRaster;

import java.io.FileNotFoundException;
import java.io.IOException;

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.videoio.VideoCapture;

public class CameraSnapshotJavaFX extends Application {
   Mat matrix = null;

   @Override
   public void start(Stage stage) throws FileNotFoundException, IOException {
     //Capturing the snapshot from the camera
      CameraSnapshotJavaFX obj = new CameraSnapshotJavaFX();
      WritableImage writableImage = obj.capureSnapShot();

     //Saving the image
      obj.saveImage();

     //Setting the image view
      ImageView imageView = new ImageView(writableImage);

     //setting the fit height and width of the image view
      imageView.setFitHeight(400);
      imageView.setFitWidth(600);

     //Setting the preserve ratio of the image view
      imageView.setPreserveRatio(true);

     //Creating a Group object
      Group root = new Group(imageView);

     //Creating a scene object
      Scene scene = new Scene(root, 600, 400);

     //Setting title to the Stage
      stage.setTitle("Capturing an image");

     //Adding scene to the stage
      stage.setScene(scene);

     //Displaying the contents of the stage
      stage.show();
   }
   public WritableImage capureSnapShot() {
      WritableImage WritableImage = null;

     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Instantiating the VideoCapture class (camera:: 0)
      VideoCapture capture = new VideoCapture(0);

     //Reading the next video frame from the camera
      Mat matrix = new Mat();
      capture.read(matrix);

     //If camera is opened
      if( capture.isOpened()) {
        //If there is next video frame
         if (capture.read(matrix)) {
           //Creating BuffredImage from the matrix
            BufferedImage image = new BufferedImage(matrix.width(),
               matrix.height(), BufferedImage.TYPE_3BYTE_BGR);

            WritableRaster raster = image.getRaster();
            DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();
            byte[] data = dataBuffer.getData();
            matrix.get(0, 0, data);
            this.matrix = matrix;

           //Creating the Writable Image
            WritableImage = SwingFXUtils.toFXImage(image, null);
         }
      }
      return WritableImage;
   }
   public void saveImage() {
     //Saving the Image
      String file = "E:/OpenCV/chap22/sanpshot.jpg";

     //Instantiating the imgcodecs class
      Imgcodecs imageCodecs = new Imgcodecs();

     //Saving it again
      imageCodecs.imwrite(file, matrix);
   }
   public static void main(String args[]) {
      launch(args);
   }
}

出力

プログラムを実行すると、次の出力が得られます。

カメラを使用してフレームをキャプチャ

指定したパスを開くと、jpgファイルとして保存されている同じフレームを確認できます。

OpenCV-画像内の顔検出

*org.opencv.videoio* パッケージの *VideoCapture* クラスには、システムカメラを使用してビデオをキャプチャするクラスとメソッドが含まれています。 段階的に行って、その方法を学びましょう。

ステップ1:OpenCVネイティブライブラリをロードする

OpenCVライブラリを使用してJavaコードを作成する場合、最初に行う必要があるステップは、* loadLibrary()*を使用してOpenCVのネイティブライブラリをロードすることです。 以下に示すように、OpenCVネイティブライブラリをロードします。

//Loading the core library
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

ステップ2:CascadeClassifierクラスをインスタンス化する

パッケージ org.opencv.objdetectCascadeClassifier クラスは、分類子ファイルをロードするために使用されます。 以下に示すように、 xml ファイル lbpcascade_frontalface.xml を渡すことにより、このクラスをインスタンス化します。

//Instantiating the CascadeClassifier
String xmlFile = "E:/OpenCV/facedetect/lbpcascade_frontalface.xml";
CascadeClassifier classifier = new CascadeClassifier(xmlFile);

ステップ3:顔を検出する

*CascadeClassifier* という名前のクラスの* detectMultiScale()*メソッドを使用して、画像内の顔を検出できます。 このメソッドは、入力画像を保持する *Mat* クラスのオブジェクトと *MatOfRect* クラスのオブジェクトを受け入れて、検出された顔を保存します。
//Detecting the face in the snap
MatOfRect faceDetections = new MatOfRect();
classifier.detectMultiScale(src, faceDetections);

次のプログラムは、画像内の顔を検出する方法を示しています。

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;

import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;

public class FaceDetectionImage {
   public static void main (String[] args) {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap23/facedetection_input.jpg";
      Mat src = Imgcodecs.imread(file);

     //Instantiating the CascadeClassifier
      String xmlFile = "E:/OpenCV/facedetect/lbpcascade_frontalface.xml";
      CascadeClassifier classifier = new CascadeClassifier(xmlFile);

     //Detecting the face in the snap
      MatOfRect faceDetections = new MatOfRect();
      classifier.detectMultiScale(src, faceDetections);
      System.out.println(String.format("Detected %s faces",
         faceDetections.toArray().length));

     //Drawing boxes
      for (Rect rect : faceDetections.toArray()) {
         Imgproc.rectangle(
            src,                                              //where to draw the box
            new Point(rect.x, rect.y),                           //bottom left
            new Point(rect.x + rect.width, rect.y + rect.height),//top right
            new Scalar(0, 0, 255),
            3                                                    //RGB colour
         );
      }

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap23/facedetect_output1.jpg", src);

      System.out.println("Image Processed");
   }
}

上記のプログラムで指定された入力画像 facedetection_input.jpg が次のものであると仮定します。

顔検出入力

出力

プログラムを実行すると、次の出力が得られます-

Detected 3 faces
Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

顔検出出力

OpenCV-カメラを使用した顔検出

次のプログラムは、システムカメラを使用して顔を検出し、JavaFXウィンドウを使用して表示する方法を示しています。

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.WritableRaster;

import java.io.FileNotFoundException;
import java.io.IOException;

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import org.opencv.videoio.VideoCapture;

public class faceDetectionJavaFXX extends Application {
   Mat matrix = null;

   @Override
   public void start(Stage stage) throws FileNotFoundException, IOException {
     //Capturing the snapshot from the camera
      faceDetectionJavaFXX obj = new faceDetectionJavaFXX();
      WritableImage writableImage = obj.capureFrame();

     //Saving the image
      obj.saveImage();

     //Setting the image view
      ImageView imageView = new ImageView(writableImage);

     //setting the fit height and width of the image view
      imageView.setFitHeight(400);
      imageView.setFitWidth(600);

     //Setting the preserve ratio of the image view
      imageView.setPreserveRatio(true);

     //Creating a Group object
      Group root = new Group(imageView);

     //Creating a scene object
      Scene scene = new Scene(root, 600, 400);

     //Setting title to the Stage
      stage.setTitle("Capturing an image");

     //Adding scene to the stage
      stage.setScene(scene);

     //Displaying the contents of the stage
      stage.show();
   }
   public WritableImage capureFrame() {
      WritableImage writableImage = null;

     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Instantiating the VideoCapture class (camera:: 0)
      VideoCapture capture = new VideoCapture(0);

     //Reading the next video frame from the camera
      Mat matrix = new Mat();
      capture.read(matrix);

     //If camera is opened
      if(!capture.isOpened()) {
         System.out.println("camera not detected");
      } else
         System.out.println("Camera detected ");

     //If there is next video frame
      if (capture.read(matrix)) {
        ///////Detecting the face in the snap/////
         String file = "E:/OpenCV/facedetect/lbpcascade_frontalface.xml";
         CascadeClassifier classifier = new CascadeClassifier(file);

         MatOfRect faceDetections = new MatOfRect();
         classifier.detectMultiScale(matrix, faceDetections);
         System.out.println(String.format("Detected %s faces",
            faceDetections.toArray().length));

        //Drawing boxes
         for (Rect rect : faceDetections.toArray()) {
            Imgproc.rectangle(
               matrix,                                  //where to draw the box
               new Point(rect.x, rect.y),                           //bottom left
               new Point(rect.x + rect.width, rect.y + rect.height),//top right
               new Scalar(0, 0, 255)                                //RGB colour
            );
         }
        //Creating BuffredImage from the matrix
         BufferedImage image = new BufferedImage(matrix.width(), matrix.height(),
            BufferedImage.TYPE_3BYTE_BGR);

         WritableRaster raster = image.getRaster();
         DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();
         byte[] data = dataBuffer.getData();
         matrix.get(0, 0, data);

         this.matrix = matrix;

        //Creating the Writable Image
         writableImage = SwingFXUtils.toFXImage(image, null);
      }
      return writableImage;
   }
   public void saveImage() {
     //Saving the Image
      String file = "E:/OpenCV/chap23/facedetected.jpg";

     //Instantiating the imagecodecs class
      Imgcodecs imageCodecs = new Imgcodecs();

     //Saving it again
      imageCodecs.imwrite(file, matrix);
   }
   public static void main(String args[]) {
      launch(args);
   }
}

出力

プログラムを実行すると、次の出力が得られます。

カメラを使用した顔検出

指定したパスを開くと、同じスナップショットが jpg 画像として保存されていることがわかります。

OpenCV-アフィン翻訳

imgprocクラスの* warpAffine()*メソッドを使用して、画像に対して*アフィン変換*を実行できます。 以下は、このメソッドの構文です-

Imgproc.warpAffine(src, dst, tranformMatrix, size);

このメソッドは、次のパラメータを受け入れます-

  • src -この操作のソース(入力画像)を表す Mat オブジェクト。
  • dst -この操作の宛先(出力イメージ)を表す Mat オブジェクト。
  • tranformMatrix -変換行列を表す Mat オブジェクト。
  • サイズ-出力画像のサイズを表す整数型の変数。

次のプログラムは、特定の画像にアフィン操作を適用する方法を示しています。

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.Point;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class AffineTranslation {
   public static void main(String args[]) {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap24/transform_input.jpg";
      Mat src = Imgcodecs.imread(file);

     //Creating an empty matrix to store the result
      Mat dst = new Mat();

      Point p1 = new Point( 0,0 );
      Point p2 = new Point( src.cols() - 1, 0 );
      Point p3 = new Point( 0, src.rows() - 1 );
      Point p4 = new Point( src.cols()*0.0, src.rows()*0.33 );
      Point p5 = new Point( src.cols()*0.85, src.rows()*0.25 );
      Point p6 = new Point( src.cols()*0.15, src.rows()*0.7 );

      MatOfPoint2f ma1 = new MatOfPoint2f(p1,p2,p3);
      MatOfPoint2f ma2 = new MatOfPoint2f(p4,p5,p6);

     //Creating the transformation matrix
      Mat tranformMatrix = Imgproc.getAffineTransform(ma1,ma2);

     //Creating object of the class Size
      Size size = new Size(src.cols(), src.cols());

     //Applying Wrap Affine
      Imgproc.warpAffine(src, dst, tranformMatrix, size);

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap24/Affinetranslate.jpg", dst);

      System.out.println("Image Processed");
   }
}

上記のプログラムで指定された入力画像 transform_input.jpg が次のものであると仮定します。

入力を変換

出力

それを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

アフィン翻訳

OpenCV-回転

*imgproc* クラスの* warpAffine()*メソッドを使用して、画像に対して*回転*操作を実行できます。 以下は、このメソッドの構文です-
Imgproc.warpAffine(src, dst, rotationMatrix, size);

このメソッドは、次のパラメータを受け入れます-

  • src -この操作のソース(入力画像)を表す Mat オブジェクト。
  • dst -この操作の宛先(出力イメージ)を表す Mat オブジェクト。
  • rotationMatrix -回転行列を表す Mat オブジェクト。
  • サイズ-出力画像のサイズを表す整数型の変数。

次のプログラムは、画像を回転させる方法を示しています。

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Size;

import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class Rotation {
   public static void main(String args[]) {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap24/transform_input.jpg";
      Mat src = Imgcodecs.imread(file);

     //Creating an empty matrix to store the result
      Mat dst = new Mat();

     //Creating a Point object
      Point point = new Point(300, 200)

     //Creating the transformation matrix M
      Mat rotationMatrix = Imgproc.getRotationMatrix2D(point, 30, 1);

     //Creating the object of the class Size
      Size size = new Size(src.cols(), src.cols());

     //Rotating the given image
      Imgproc.warpAffine(src, dst, rotationMatrix, size);

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap24/rotate_output.jpg", dst);

      System.out.println("Image Processed");
   }
}

上記のプログラムで指定された入力画像 transform_input.jpg が次のものであると仮定します。

入力を変換

出力

プログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

出力の回転

OpenCV-スケーリング

*imgproc* クラスの* resize()*メソッドを使用して、画像に対して*スケーリング*を実行できます。 このメソッドの構文は次のとおりです。
resize(Mat src, Mat dst, Size dsize, double fx, double fy, int interpolation)

このメソッドは、次のパラメータを受け入れます-

  • src -この操作のソース(入力画像)を表す Mat オブジェクト。
  • dst -この操作の宛先(出力イメージ)を表す Mat オブジェクト。
  • dsize -出力画像のサイズを表す Size オブジェクト。
  • fx -水平軸に沿ってスケール係数を表すdouble型の変数。
  • fy -垂直軸に沿ったスケール係数を表すdouble型の変数。
  • Interpolation -補間方法を表す整数変数。

次のプログラムは、*スケール変換*を画像に適用する方法を示しています。

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Size;

import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class Scaling {
   public static void main(String args[]) {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap24/transform_input.jpg";
      Mat src = Imgcodecs.imread(file);

     //Creating an empty matrix to store the result
      Mat dst = new Mat();

     //Creating the Size object
      Size size = new Size(src.rows()*2, src.rows()*2);

     //Scaling the Image
      Imgproc.resize(src, dst, size, 0, 0, Imgproc.INTER_AREA);

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap24/scale_output.jpg", dst);

      System.out.println("Image Processed");
   }
}

上記のプログラムで指定された入力画像 transform_input.jpg (サイズ-幅:300pxおよび高さ:300px)が次のものであると仮定します。

入力を変換

出力

プログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます(サイズ-幅:600pxおよび高さ:600px)-

スケール出力

OpenCV-カラーマップ

OpenCVでは、クラス Imgproc のメソッド* applyColorMap()*を使用して、さまざまなカラーマップを画像に適用できます。 以下は、このメソッドの構文です-

applyColorMap(Mat src, Mat dst, int colormap)

それは3つのパラメータを受け入れます-

  • src -ソース(入力)画像を表すクラス Mat のオブジェクト。
  • dst -宛先(出力)イメージを表すクラス Mat のオブジェクト。
  • colormap -適用されるカラーマップのタイプを表す整数タイプの変数。

次のプログラムは、*カラーマップ*を画像に適用する方法を示しています。

import org.opencv.core.Core;
import org.opencv.core.Mat;

import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class ColorMapTest {
   public static void main(String args[]) {
     //Loading the OpenCV core library
      System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap25/color_input.jpg";
      Mat src = Imgcodecs.imread(file);

     //Creating an empty matrix to store the result
      Mat dst = new Mat();

     //Applying color map to an image
      Imgproc.applyColorMap(src, dst, Imgproc.COLORMAP_HOT);

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap25/colormap_hot.jpg", dst);
      System.out.println("Image processed");
   }
}

上記のプログラムで指定された入力画像 color_input.jpg が次のものであると仮定します。

カラー入力

出力

上記のプログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

カラー出力

その他の操作

前の例で示した COLORMAP_HOT に加えて、OpenCVはさまざまなタイプのカラーマップを提供します。 これらのタイプはすべて、Imgprocクラスの事前定義された静的フィールド(固定値)によって表されます。

  • applyColorMap()メソッドの *colormap という名前のパラメーターにそれぞれの定義済みの値を渡すことにより、必要なカラーマップのタイプを選択できます。
Imgproc.applyColorMap(src, dst, Imgproc.COLORMAP_HOT);

以下は、さまざまなタイプのカラーマップとそれぞれの出力を表す値です。

Operation and Description Output
COLORMAP_AUTUMN COLORMAP_AUTUMN
COLORMAP_BONE COLORMAP_BONE
COLORMAP_COOL COLORMAP_COOL
COLORMAP_HOT COLORMAP_HOT
COLORMAP_HSV COLORMAP_HSV
COLORMAP_JET COLORMAP_JET
COLORMAP_OCEAN COLORMAP_OCEAN
COLORMAP_PARULA COLORMAP_PARULA
COLORMAP_PINK COLORMAP_PINK
COLORMAP_RAINBOW COLORMAP_RAINBOW
COLORMAP_SPRING COLORMAP_SPRING
COLORMAP_SUMMER COLORMAP_SUMMER
COLORMAP_WINTER COLORMAP_WINTER

OpenCV-キャニーエッジ検出

Canny Edge Detectionは、画像のエッジを検出するために使用されます。 入力としてグレースケール画像を受け入れ、多段アルゴリズムを使用します。

*imgproc* クラスの* Canny()*メソッドを使用して、この操作を画像で実行できます。このメソッドの構文は次のとおりです。
Canny(image, edges, threshold1, threshold2)

このメソッドは、次のパラメータを受け入れます-

  • image -この操作のソース(入力画像)を表す Mat オブジェクト。
  • edges -この操作の宛先(エッジ)を表す Mat オブジェクト。
  • threshold1 -ヒステリシス手順の最初のしきい値を表すdouble型の変数。
  • threshold2 -ヒステリシス手順の2番目のしきい値を表すdouble型の変数。

次のプログラムは、特定の画像でCanny Edge Detection操作を実行する方法を示す例です。

import org.opencv.core.Core;
import org.opencv.core.Mat;

import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class CannyEdgeDetection {
   public static void main(String args[]) throws Exception {
     //Loading the OpenCV core library
      System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

     //Reading the Image from the file and storing it in to a Matrix object
      String file = "E:/OpenCV/chap17/canny_input.jpg";

     //Reading the image
      Mat src = Imgcodecs.imread(file);

     //Creating an empty matrix to store the result
      Mat gray = new Mat();

     //Converting the image from color to Gray
      Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
      Mat edges = new Mat();

     //Detecting the edges
      Imgproc.Canny(gray, edges, 60, 60*3);

     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap17/canny_output.jpg", edges);
      System.out.println("Image Loaded");
   }
}

上記のプログラムで指定された入力画像 canny_input.jpg が次のものであると仮定します。

キャニー入力

出力

上記のプログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

キャニー出力

OpenCV-ハフ線変換

*Imgproc* クラスのメソッド* HoughLines()*を使用して* Hough変換手法*を適用することにより、特定の画像の形状を検出できます。 このメソッドの構文は次のとおりです。
HoughLines(image, lines, rho, theta, threshold)

このメソッドは、次のパラメータを受け入れます-

  • image -ソース(入力)イメージを表すクラス Mat のオブジェクト。
  • lines -線のパラメーター(r、Φ)を格納するベクトルを格納するクラス Mat のオブジェクト。
  • rho -パラメータrの解像度をピクセル単位で表すdouble型の変数。
  • theta -ラジアン単位のパラメータΦの解像度を表すdouble型の変数。
  • threshold -線を「検出」する交差点の最小数を表す整数型の変数。

次のプログラムは、特定の画像でハフ線を検出する方法を示しています。

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;

import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class HoughlinesTest {
   public static void main(String args[]) throws Exception {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file = "E:/OpenCV/chap21/hough_input.jpg";

     //Reading the image
      Mat src = Imgcodecs.imread(file,0);

     //Detecting edges of it
      Mat canny = new Mat();
      Imgproc.Canny(src, canny, 50, 200, 3, false);

     //Changing the color of the canny
      Mat cannyColor = new Mat();
      Imgproc.cvtColor(canny, cannyColor, Imgproc.COLOR_GRAY2BGR);

     //Detecting the hough lines from (canny)
      Mat lines = new Mat();
      Imgproc.HoughLines(canny, lines, 1, Math.PI/180, 100);

      System.out.println(lines.rows());
      System.out.println(lines.cols());

     //Drawing lines on the image
      double[] data;
      double rho, theta;
      Point pt1 = new Point();
      Point pt2 = new Point();
      double a, b;
      double x0, y0;

      for (int i = 0; i < lines.cols(); i++) {
         data = lines.get(0, i);
         rho = data[0];
         theta = data[1];

         a = Math.cos(theta);
         b = Math.sin(theta);
         x0 = a*rho;
         y0 = b*rho;

         pt1.x = Math.round(x0 + 1000*(-b));
         pt1.y = Math.round(y0 + 1000*(a));
         pt2.x = Math.round(x0 - 1000*(-b));
         pt2.y = Math.round(y0 - 1000 *(a));
         Imgproc.line(cannyColor, pt1, pt2, new Scalar(0, 0, 255), 6);
      }
     //Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap21/hough_output.jpg", cannyColor);

      System.out.println("Image Processed");
   }
}

上記のプログラムで指定された入力画像 hough_input.jpg が次のものであると仮定します。

ハフ入力

出力

プログラムを実行すると、次の出力が得られます-

143
1
Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

ハフ出力

OpenCV-ヒストグラム均等化

画像の「ヒストグラム」は、ピクセルの強度値の頻度を示します。 画像ヒストグラムでは、X軸はグレーレベルの強度を示し、Y軸はこれらの強度の頻度を示します。

ヒストグラムの均等化*は、強度範囲を広げるために、画像のコントラストを改善します。 *Imgproc クラスの* equalizeHist()*メソッドを使用して、特定の画像のヒストグラムを均等化できます。 このメソッドの構文は次のとおりです。

equalizeHist(src, dst)

このメソッドは、次のパラメータを受け入れます-

  • src -ソース(入力)画像を表すクラス Mat のオブジェクト。
  • dst -出力を表すクラス Mat のオブジェクト。 (ヒストグラムを等化した後に得られた画像)

次のプログラムは、特定の画像のヒストグラムを均等化する方法を示しています。

import java.util.ArrayList;
import java.util.List;

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

public class HistoTest {
   public static void main (String[] args) {
     //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

     //Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap20/histo_input.jpg";

     //Load the image
      Mat img = Imgcodecs.imread(file);

     //Creating an empty matrix
      Mat equ = new Mat();
      img.copyTo(equ);

     //Applying blur
      Imgproc.blur(equ, equ, new Size(3, 3));

     //Applying color
      Imgproc.cvtColor(equ, equ, Imgproc.COLOR_BGR2YCrCb);
      List<Mat> channels = new ArrayList<Mat>();

     //Splitting the channels
      Core.split(equ, channels);

     //Equalizing the histogram of the image
      Imgproc.equalizeHist(channels.get(0), channels.get(0));
      Core.merge(channels, equ);
      Imgproc.cvtColor(equ, equ, Imgproc.COLOR_YCrCb2BGR);

      Mat gray = new Mat();
      Imgproc.cvtColor(equ, gray, Imgproc.COLOR_BGR2GRAY);
      Mat grayOrig = new Mat();
      Imgproc.cvtColor(img, grayOrig, Imgproc.COLOR_BGR2GRAY);

      Imgcodecs.imwrite("E:/OpenCV/chap20/histo_output.jpg", equ);
      System.out.println("Image Processed");
   }
}

上記のプログラムで指定された入力画像 histo_input.jpg が次のものであると仮定します。

Histo Input

出力

プログラムを実行すると、次の出力が得られます-

Image Processed

指定したパスを開くと、次のように出力画像を観察できます-

Histo Output