Creating a 3D Lantern with Python: Step‑by‑Step Tutorial
This tutorial demonstrates how to use Python with NumPy, Pillow, and the wxgl library to generate a 3D lantern model by loading a paper texture, constructing a cylindrical skeleton, mapping the texture onto it, and rendering the final lantern with optional decorative elements.
The article introduces the traditional Chinese Lantern Festival and proposes a Python project that creates a 3D lantern model using image textures and simple geometric calculations.
Materials : a paper image (PNG) that will serve as the lantern skin; any custom patterns or text can be added to this image.
Python environment and required modules : a computer with Python installed and the following packages: numpy , Pillow , and wxgl .
Construction steps :
1. Load the paper image and convert it to a NumPy array normalized to the range [0, 1].
>> import numpy as np
>>> from PIL import Image
>>> import wxgl.wxplot as plt
>>> fn = r'D:\temp\light0115\res\paper.png'
>>> im = np.array(Image.open(fn)) / 255
>>> rows, cols, deep = im.shape2. Compute the dimensions of the cylindrical skeleton (radius = 1 unit, height = 2.668 units) based on the image size.
>> r = 1
>>> h = 2 * np.pi * rows / cols
>>> theta = np.linspace(0, 2*np.pi, cols)
>>> x = r * np.cos(theta)
>>> y = r * np.sin(theta)
>>> z = np.linspace(0, h, rows)
>>> xs = np.tile(x, (rows, 1))
>>> ys = np.tile(y, (rows, 1))
>>> zs = z.repeat(cols).reshape((rows, cols))3. Visualize the skeleton using plt.mesh (optionally sampling every 10 points for clarity).
>> plt.mesh(xs[::10, ::10], ys[::10, ::10], zs[::10, ::10], mode='FLBL')
>>> plt.show()4. Map the paper texture onto the skeleton. If the texture appears upside‑down, reverse its vertical axis.
>> plt.mesh(xs, ys, zs, im) # original orientation
>>> plt.mesh(xs, ys, zs, im[::-1]) # flipped orientation
>>> plt.show()5. Add decorative elements such as a colored frame, a central sphere, and a colored curve to complete the lantern appearance.
>> plt.surface(vs, color='#C03000', method='T', mode='FCBC', alpha=0.8)
>>> plt.sphere((0,0,h*0.4), 0.4, '#FFFFFF', slices=60, mode='FCBC')
>>> plt.plot((0,0), (0,0), (0.4*h, 1.5*h), width=3.0, style='solid', cmap='hsv', caxis='z')
>>> plt.show(rotation='h-')The full script combining all steps is provided at the end of the article, enabling readers to run the program directly in Python IDLE and generate their own 3D lanterns for the Lantern Festival.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.