[英]How can I convert OpenCV Mat to Texture2D in Unity using C# script?
我只想將Mat類型變量轉換為Texture2D類型。
我可以將texture2D轉換為mat,這只能使用EncodeToJPG()函數。 像這樣:
Mat mat = Mat.FromImageData(_texture.EncodeToPNG());
Texture2D-> Mat很容易...但是我不能轉換“ MAT-> Texture2D”
對於opencvsharp,請使用Mat.GetArray
來獲取mat的字節數組數據,然后根據mat的高度和寬度在其上循環。 在該循環中將mat數據復制到Color32
,最后使用Texture2D.SetPixels32()
和Texture2D.Apply()
設置和應用像素。
void MatToTexture(Mat sourceMat)
{
//Get the height and width of the Mat
int imgHeight = sourceMat.Height;
int imgWidth = sourceMat.Width;
byte[] matData = new byte[imgHeight * imgWidth];
//Get the byte array and store in matData
sourceMat.GetArray(0, 0, matData);
//Create the Color array that will hold the pixels
Color32[] c = new Color32[imgHeight * imgWidth];
//Get the pixel data from parallel loop
Parallel.For(0, imgHeight, i => {
for (var j = 0; j < imgWidth; j++) {
byte vec = matData[j + i * imgWidth];
var color32 = new Color32 {
r = vec,
g = vec,
b = vec,
a = 0
};
c[j + i * imgWidth] = color32;
}
});
//Create Texture from the result
Texture2D tex = new Texture2D(imgWidth, imgHeight, TextureFormat.RGBA32, true, true);
tex.SetPixels32(c);
tex.Apply();
}
如果您不是使用opencvsharp,而是使用C ++和C#自己制作插件,請參閱這篇文章。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.