Skip to content

Instantly share code, notes, and snippets.

@n-taku
Last active March 1, 2020 04:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n-taku/9950a92a087373d925c24e5c131605a7 to your computer and use it in GitHub Desktop.
Save n-taku/9950a92a087373d925c24e5c131605a7 to your computer and use it in GitHub Desktop.
Physics.Raycastを飛ばして,当たったオブジェクトのuv座標を取得して,対応する場所のtextureの色を書き換える [blog](https://unitech.hatenablog.com/entry/2020/02/29/144249)
using UnityEngine;
using UnityEngine.UI;
public class Paint : MonoBehaviour
{
const int width = 28;
const int height = 28;
public MeshRenderer m;
public Button b;
public Text answer;
private Texture2D texture;
private readonly Color[] buffer = new Color[width * height];
private readonly float[] input = new float[width * height];
private MnistInference mnistInference;
private void Start()
{
mnistInference = new MnistInference(Application.dataPath + "/MLModel/model.onnx");
texture = new Texture2D(width, height);
m.material.mainTexture = texture;
ClearBuffer();
}
private void Update()
{
//クリック座標を白く塗りつぶす
if (Input.GetMouseButton(0))
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out var hit, 100.0f))
{
var pixel = new Vector2(hit.textureCoord.x * width, hit.textureCoord.y * height);
Draw(Vector2Int.RoundToInt(pixel));
}
texture.SetPixels(buffer);
texture.Apply();
}
//塗りつぶした部分を1としてfloatの配列に代入
for (int i = 0; i < buffer.Length; i++)
{
input[i] = buffer[i].r;
}
//推論
var num = mnistInference.Inference(input);
answer.text = num.ToString();
}
//4ピクセル塗る
private void Draw(Vector2Int p)
{
DrawBuffer(p.x, p.y);
DrawBuffer(p.x + 1, p.y);
DrawBuffer(p.x + 1, p.y + 1);
DrawBuffer(p.x, p.y + 1);
}
//バッファーに書き込む
private void DrawBuffer(int x, int y)
{
if (x < 0 || width <= x || y < 0 || height <= y)
{
return;
}
buffer.SetValue(Color.white, x + width * y);
}
//黒(0)で塗りつぶしてクリア
public void ClearBuffer()
{
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = Color.black;
}
texture.SetPixels(buffer);
texture.Apply();
}
}
@n-taku
Copy link
Author

n-taku commented Mar 1, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment