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

การแสดง NumPy 2D Array เป็นภาพ Grayscale ใน Jupyter Notebook

ขั้นตอนการทำงาน

  • กำหนดขนาดรูปภาพและปรับระยะห่างรอบๆ subplots

  • สร้างข้อมูลสุ่มด้วย NumPy

  • แสดงข้อมูลเป็นภาพ 2D raster ด้วย Colormap gray

  • แสดงรูปภาพด้วยเมธอด show()

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

from matplotlib import pyplot as plt
import numpy as np

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

# ข้อมูลสุ่ม 5x5
data = np.random.rand(5, 5)

# แสดงภาพด้วย imshow และ colormap gray
plt.imshow(data, cmap='gray')
plt.show()

ผลลัพธ์

ภาพ Grayscale 5x5 พิกเซล ค่าสูง = สีขาว ค่าต่ำ = สีดำ เหมาะสำหรับแสดงภาพขาวดำ Heatmap หรือ Matrix

Colormap อื่นๆ ที่น่าสนใจ: viridis, plasma, inferno, magma, hot, cool สำหรับข้อมูลที่ไม่ใช่ grayscale