質問

I would like to know how can I create a Texture3D from a Texture2D.

enter image description here

I've found some good examples : Unity 4 - 3D Textures (Volumes) or Unity - 3D Textures or Color Correction Lookup Texture

int     dim = tex2D.height;
Color[] c2D = tex2D.GetPixels();
Color[] c3D = new Color[c2D.Length];
for (int x = 0; x < dim; ++x)
{
    for (int y = 0; y < dim; ++y)
    {
        for (int z = 0; z < dim; ++z)
        {
            int y_ = dim - y - 1;
            c3D[x + (y * dim) + (z * dim * dim)] = c2D[z * dim + x + y_ * dim * dim];
        }
    }
}

But this only works when you have

Texture2D.height= Mathf.FloorToInt(Mathf.Sqrt(Texture2D.width))

or if

Depth = Width = Height

How can I extract the values when the depth is not equal to the width or the height ? It seems simple but I am missing something...

Thank you very much.

役に立ちましたか?

解決

You can split the texture as follows:

//Iterate the result
for(int z = 0; z < depth; ++z)
    for(int y = 0; y < height; ++y)
        for(int x = 0; x < width; ++x)
            c3D[x + y * width + z * width * height]
              = c2D[x + y * width * depth + z * width]

You can get to this index formula as follows:

Advancing by 1 in the x-direction results in an increment by 1 (just the next pixel).

Advancing by 1 in the y-direction results in an increment by depth * width (skip 4 images with the according width).

Advancing by 1 in the z-direction results in an increment by width (skip one image row).

Or if you prefer the other direction:

//Iterate the original image
for(int y = 0; y < height; ++y)
    for(int x = 0; x < width * depth; ++x)
         c3D[(x % width) + y * width + (x / width) * width * height] = c2D[x + y * width * depth];

他のヒント

Unfortunately, there's not much documentation about the 3DTexture. I've tried to simply use the c2D as the Texture's data but it doesn't give an appropriate result.

For the moment I tried this which gives better result but I don't know of it's correct.

for (int x = 0; x < width; ++x)
{
    for (int y = 0; y < height; ++y)
    {
        for (int z = 0; z < depth; ++z)
        {
            int y_ = height - y - 1;
            c3D[x + (y * height) + (z * height * depth)] = c2D[z * height + x + y_ * height * depth];
        }
    }
}

From your picture, it looks like you have the planes of the 3D texture you want side by side? So you want a 3D texture with dimensions (width, height, depth) from a 2D texture with (width * depth, height)? You should be able to do this with something like this:

for (int z = 0; z < depth; ++z)
{
    for (int y = 0; y < height; ++y)
    {
        memcpy(c3D + (z * height + y) * width, c2D + (y * depth + z) * width, width * sizeof(Color));
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top