从纹理中获取Unity 5 GetPixels,然后在另一个纹理上使用SetPixels,这会弄得一团糟

时间:2016-04-15 08:04:56

标签: c# unity3d webcam unity5

我正试图从使用WebCamTexture拍摄的照片中获取玩家的脸部,然后将其应用于3D模型的纹理,以便玩家的脸部将替换模型中的某个。我有照片,我已经准备混合了纹理,但我尝试了不同的方式,有两个周期和一个getPixels到区域,但没有,只在我需要编辑的区域出现一个混乱的正方形(右边)区域)。下图显示了我的需求:

The Result

编辑: 这就是我试过的:

    //path of the photo taken
_SavePath = Application.dataPath+"/Snap";
//The texture of the photo taken from WebCamTexture (my webcam output is 800x600)
Texture2D snap = new Texture2D(wct.width, wct.height);
//The texture of the 3D model (800x800 px) that I need to edit to apply a section of the photo taken (snap texture)
Texture2D texFace = new Texture2D(OrigText.width, OrigText.height);
//set pixels of the photo
snap.SetPixels(wct.GetPixels());
snap.Apply();
//This divides the image into logic squares so find the points from where to start the loop to get the section of the photo (based on the webcam output resolution) 
int sc_ux = snap.width / 8;
int sc_uy = snap.height / 6;
//same here for the final 3D Model texture
int te_ux = texFace.width / 6;
int te_uy = texFace.height / 6;
//Getting the points 
int x1 = sc_ux * 3;
int y1 = sc_uy * 2;
int x2 = sc_ux * 5;
int y2 = sc_uy * 5;
int x3 = te_ux * 2;
int y3 = te_uy * 1;
int x4 = te_ux * 4;
int y4 = te_uy * 4;

int xx = x1;
int yy = y1;
//same of SetPixels function, I've tried with a loop too. Here I create a copy of the original texture (OrigText) to texFace.
for (int y = 0; y < OrigText.height; y++) {
    for (int x = 0; x < OrigText.width; x++) {
        texFace.SetPixel (x, y, OrigText.GetPixel (x, y));
    }
}
texFace.Apply ();
//Then I loop starti from the area that I need to change with the pixels of the area I need from snap texture (photo taken from webcam)
for (int y = y3; y <= y4; y++) {
    for (int x = x3; x <= x4; x++) {
        Color getcolor = snap.GetPixel(xx, yy);
        texFace.SetPixel (x, y, getcolor);
        xx += 1;
    }
    yy += 1;
}
//apply
texFace.Apply();

这就是我从中得到的:

Not what I want

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

我建议你研究一下使用RenderTexture而不是从数组中复制像素,这样你就可以更好地控制你正在做的事情了。您可以使用Unity UI并将两个纹理渲染到渲染纹理目标,其中一个具有头部纹理,然后将拍摄的照片的相机馈送到纹理的四边形上,当渲染这些东西时,我将获得渲染的像素纹理并使用renderTextureTarget.EncodeToPNG()将其编码为PNG,然后保存到磁盘并稍后加载到3d模型上: - )

答案 1 :(得分:0)

从Unity 5.4b-5中,您可以使用Graphics.CopyTexture将纹理的全部或部分内容复制到另一个纹理上。