MiniUFO
MiniUFO

Reputation: 306

RBG image as texture for a 3D cube using matplotlib

I want to plot a 3D cube using matplotlib, and map an arbitary RGB image (jpg or png) as a texture to each side of the cube. There is a good example here using matlab.

enter image description here

I just wonder how to do it using Python/matplotlib, possibly starting from this example.

Upvotes: 1

Views: 2181

Answers (1)

MiniUFO
MiniUFO

Reputation: 306

I figured it out myself and the following is the code:

import numpy as np
import matplotlib.image as image
import matplotlib.pyplot as plt

C = image.imread('d:/timg.png')

xp, yp, __ = C.shape

x = np.arange(0, xp, 1)
y = np.arange(0, yp, 1)
Y, X = np.meshgrid(y, x)

fig = plt.figure(figsize=(12,9))
ax = fig.gca(projection='3d')
ax.dist=6.2
ax.view_init(elev=38, azim=-45)

ax.plot_surface(X, Y, X-X+yp, facecolors=C,
                rstride=2, cstride=2,
                antialiased=True, shade=False)

ax.plot_surface(X, X-X, Y, facecolors=np.fliplr(C.transpose((1,0,2))),
                rstride=2, cstride=2,
                antialiased=True, shade=False)

ax.plot_surface(X-X+xp, X, Y, facecolors=np.fliplr(C.transpose((1,0,2))),
                rstride=2, cstride=2,
                antialiased=True, shade=False)

The resulting image is:

3D texture

Changing the stride to 1 will get more detail of the png image, but it seems that it is not a very efficient way, especially when the image size is very large.

Upvotes: 5

Related Questions