[英]Convert Texture2D to OpenCV Mat?
There is a post about converting OpenCV cv::Mat
to Texture2D
in Unity and I provided an answer which works well. 有一个帖子关于如何将OpenCV的cv::Mat
到Texture2D
团结我提供了行之有效的答案。 Now, I am trying to do the opposite but have been stuck on this for few hours now. 现在,我正试图做相反的事情,但是已经坚持了几个小时。
I want to convert Unity's Texture2D
to OpenCV cv::Mat
so that I can process the Texture on the C++ side. 我想将Unity的Texture2D
转换为OpenCV cv::Mat
以便可以在C ++端处理Texture。
Here is the original Texture2D
in my Unity project that I want to convert to cv:Mat
: 这是我要转换为cv:Mat
Unity项目中的原始Texture2D
:
Here is what it looks like after converting it into cv:Mat
: 将其转换为cv:Mat
之后的样子如下:
It looks so washed out. 它看起来很褪色。 I am not worried about the rotation of the image . 我不担心图像的旋转 。 I can fix that. 我可以解决。 Just wondering why it looks so washed out. 只是想知道为什么它看起来这么洗掉了。 Also used cv::imwrite
to save the image for testing purposes but the issue in also in the saved image. 还使用cv::imwrite
来保存图像以进行测试,但是问题也存在于已保存的图像中。
C# code : C#代码 :
[DllImport("TextureConverter")]
private static extern float TextureToCVMat(IntPtr texData, int width, int height);
unsafe void TextureToCVMat(Texture2D texData)
{
Color32[] texDataColor = texData.GetPixels32();
//Pin Memory
fixed (Color32* p = texDataColor)
{
TextureToCVMat((IntPtr)p, texData.width, texData.height);
}
}
public Texture2D tex;
void Start()
{
TextureToCVMat(tex);
}
C++ code : C ++代码 :
DLLExport void TextureToCVMat(unsigned char* texData, int width, int height)
{
Mat texture(height, width, CV_8UC4, texData);
cvNamedWindow("Unity Texture", CV_WINDOW_NORMAL);
//cvResizeWindow("Unity Texture", 200, 200);
cv::imshow("Unity Texture", texture);
cv::imwrite("Inno Image.jpg", texture);
}
I also tried creating a struct
on the C++ side to hold the pixel information instead of using unsigned char*
but the result is still the-same: 我还尝试在C ++端创建一个struct
来保存像素信息,而不是使用unsigned char*
但结果仍然相同:
struct Color32
{
uchar r;
uchar g;
uchar b;
uchar a;
};
DLLExport void TextureToCVMat(Color32* texData, int width, int height)
{
Mat texture(height, width, CV_8UC4, texData);
cvNamedWindow("Unity Texture", CV_WINDOW_NORMAL);
cvResizeWindow("Unity Texture", 200, 200);
cv::imshow("Unity Texture", texture);
}
Why does the image look so so washed out and how do you fix this? 为什么图像看起来如此褪色,您如何解决呢?
OpenCV creates images as BGR
by default, whereas Color32
stores pixels as RGBA
. 默认情况下, OpenCV将图像创建为BGR
,而Color32
将像素存储为RGBA
。 However since OP mentioned in the comments that the Texture2D.format
gives texture format as RGB24
, we can ignore the alpha channel altogether. 但是,由于OP在注释中提到Texture2D.format
提供的纹理格式为RGB24
,因此我们可以完全忽略alpha通道。
DLLExport void TextureToCVMat(unsigned char* texData, int width, int height)
{
Mat texture(height, width, CV_8UC4, texData);
cv::cvtColor(texture,texture,cv::COLOR_BGRA2RGB);
cv::imshow("Unity Texture", texture);
cv::waitKey(0);
cv::destroyAllWindows();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.