Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การสร้าง Surface Plot จาก Grayscale Image ด้วย Matplotlib

Surface Plot 3D จากภาพ Grayscale ใช้ Intensity ของพิกเซลเป็นความสูง (Z-axis) เหมาะสำหรับการแสดงภูมิประเทศ หรือข้อมูลความหนาแน่น

ขั้นตอน

  1. ตั้งค่าขนาด Figure
  2. สร้างข้อมูลสุ่ม 2D (จำลอง Grayscale Image)
  3. สร้าง Meshgrid (XX, YY) จากขนาดภาพ
  4. สร้าง Figure และ 3D Axes
  5. วาด Surface Plot ด้วย cmap='gray'
  6. แสดงผล

ตัวอย่างโค้ด


import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# สร้างข้อมูลสุ่ม 5x5 (จำลอง grayscale image)
data = np.random.rand(5, 5)

# สร้าง meshgrid
xx, yy = np.mgrid[0:data.shape[0], 0:data.shape[1]]

fig = plt.figure()
ax = fig.gca(projection='3d')

# cmap='gray' ให้สี grayscale
ax.plot_surface(xx, yy, data, rstride=1, cstride=1, 
                linewidth=0, cmap='gray')

plt.show()

การใช้กับภาพจริง


from PIL import Image

# โหลดภาพและแปลงเป็น grayscale
img = Image.open('image.png').convert('L')
data = np.array(img)

# ลดขนาดถ้าภาพใหญ่เกินไป
# data = data[::10, ::10]  # downsample

xx, yy = np.mgrid[0:data.shape[0], 0:data.shape[1]]

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(xx, yy, data, cmap='gray', rstride=5, cstride=5)
plt.show()

พารามิเตอร์สำคัญ

  • rstride, cstride: ข้ามแถว/คอลัมน์เพื่อลดความหนาแน่น (เรนเดอร์เร็วขึ้น)
  • linewidth=0: ไม่วาดเส้นขอบ
  • cmap='gray': ใช้สี Grayscale
  • antialiased=True: ทำให้ผิวเรียบ

ผลลัพธ์

กราฟ 3D แสดงผิวที่ความสูงสอดคล้องกับค่า Intensity ของภาพ Grayscale