Skip to content

Instantly share code, notes, and snippets.

@saccadic
Last active January 24, 2021 12:14
Show Gist options
  • Save saccadic/ddb186d640cf350474323050c8ea2ad2 to your computer and use it in GitHub Desktop.
Save saccadic/ddb186d640cf350474323050c8ea2ad2 to your computer and use it in GitHub Desktop.
Unityで回帰曲線を求めるサンプル(4次方程式)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using OpenCvSharp;
namespace OpenCvSharp
{
public class polyfit : MonoBehaviour
{
[Range(0, 1)]
public float p1;
[Range(0, 1)]
public float p2;
[Range(0, 1)]
public float p3;
[Range(0, 1)]
public float p4;
[Range(0, 1)]
public float p5;
[Range(0, 1)]
public float p6;
[Range(0, 1)]
public float p7;
private float[] point_base;
private Mat pointA_mat;
private Mat pointB_mat;
private Mat param;
Mat PolynomialFeatures(float[] x, int order)
{
// 1 x x^2 x^3 x^4
Mat output = Mat.Zeros(x.Length, order+1, MatType.CV_32FC1);
for (int i = 0; i < x.Length; i++)
{
float x_value = x[i];
output.Set<float>(i, 0, 1.0f);
for (int j = 1; j < order + 1; j++)
{
// Debug.Log(Mathf.Pow(x_value, (float)j));
output.Set<float>(i, j, Mathf.Pow(x_value, (float)j));
}
}
return output.Clone();
}
void debugMat(Mat src)
{
string str = "";
for (int i = 0; i < src.Height; i++)
{
for (int j = 0; j < src.Width; j++)
{
//Debug.Log(src.Get<float>(i, j));
str += src.Get<float>(i, j).ToString() + ",";
}
str += "\n";
}
Debug.Log(str);
}
// Start is called before the first frame update
void Start()
{
point_base = new float[9];
point_base[0] = 0.0f;
point_base[1] = 0.1230469f;
point_base[2] = 0.2480469f;
point_base[3] = 0.3730469f;
point_base[4] = 0.4980469f;
point_base[5] = 0.6231689f;
point_base[6] = 0.7481689f;
point_base[7] = 0.8731689f;
point_base[8] = 1.0f;
pointA_mat = PolynomialFeatures(point_base,4);
pointB_mat = Mat.Zeros(point_base.Length, 1, MatType.CV_32FC1);
param = Mat.Zeros(5, 1, MatType.CV_32FC1);
debugMat(pointA_mat);
debugMat(pointB_mat);
debugMat(param);
}
// Update is called once per frame
void Update()
{
float[] pointB = {0.0f, p1, p2, p3, p4, p5, p6, p7 ,1.0f};
for (int i = 0; i < pointB.Length; i++)
{
pointB_mat.Set<float>(i, pointB[i]);
}
Cv2.Solve(pointA_mat, pointB_mat, param, DecompTypes.SVD);
param = param.Transpose();
debugMat(pointB_mat);
debugMat(param);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment