1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

OpenCVforUnity 画像を回転させる(アフィン変換処理)

Posted at

はじめに

この記事ではOpenCVforUnity(有償)を使用しています。
iOSアーカイブ目的の際はこちらをお勧めします。(Appleのbitcode変換も問題なく通るのでアップ後のアーキテクチャ対応の心配ありません)

Unityで画像を保存する際にフリップ処理したいなんて時があると思います。RendereTextreで工夫したり、ピクセル処理することもできるかと思いますが。今回はOpenCVを使います。

今回はこの結果を目指します。Texture2Dを右回転、左回転に処理します。
スクリーンショット 2020-12-06 13.39.58.png
といっても、することはPythonで使用する時と変わりません。
Texture2DをMatへ変換して回転変換を加えて再びTexture2Dへ返しているだけです。

実装方法

OpenCVManager.cs
using UnityEngine;
using OpenCVForUnity.CoreModule;
using OpenCVForUnity.UnityUtils;
using OpenCVForUnity.ImgprocModule;

public class OpenCVManager
{
    /// <summary>
    /// Texture2Dを90度アフィン変換処理 true:右回転 false:左回転
    /// </summary>
    public static Texture2D RotateAndResize(Texture2D tex, bool isRight)
    {
        Mat origin = new Mat(tex.height, tex.width, CvType.CV_8UC4);
        Utils.texture2DToMat(tex, origin);
        Mat dest = new Mat();

        //cpu生画像なので横長画像前提
        var center = new Point(origin.cols() / 2, origin.cols() / 2);
        Mat rMat = Imgproc.getRotationMatrix2D(center, 90, 1);
        Imgproc.warpAffine(origin, dest, rMat, new Size(origin.rows(), origin.cols()));

        if (isRight)
        {
            Core.flip(dest, dest, -1);
        }
        Texture2D texture = new Texture2D(dest.cols(), dest.rows(), TextureFormat.RGBA32, false);
        Utils.matToTexture2D(dest, texture);
        return texture;
    }
}

まとめ

名前空間上のどのクラスに必要な関数があるのか若干わかりにくい感じはします。
後発系のOpenCVplusUnity(無料)の方が使用感的には使いやすい印象です。
癖があるだけで慣れてしまえばどちらも同じです。
アーカイブ目的であればOpenCVforUnityをおすすめします。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?