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

วิธีอ่านไฟล์รูปภาพและแปลงเป็น Array ใน Matplotlib

ใช้ plt.imread() อ่านไฟล์ภาพเข้าสู่ NumPy Array

ขั้นตอน

  1. ตั้งค่าขนาด Figure
  2. อ่านภาพด้วย plt.imread("filename.jpg")
  3. พิมพ์ Array ออก Console
  4. ปิดแกนด้วย axis('off')
  5. แสดงภาพด้วย plt.show()

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

from matplotlib import pyplot as plt

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

im = plt.imread("forest.jpg")
print("Numpy array of the image is: ", im)

im = plt.imshow(im)
plt.axis('off')
plt.show()

ผลลัพธ์

แสดงภาพและพิมพ์ NumPy Array (ค่า RGB 0-255) ใน Console

วิธีอ่านไฟล์รูปภาพและแปลงเป็น Array ใน Matplotlib

[[[ 47 129 211]  [ 47 129 211]  [ 49 130 212] ...  [ 50 76 109]  [ 52 77 108]  [ 41 66 97]]
 [[ 47 129 211]  [ 47 129 211]  [ 49 130 212] ...  [ 43 69 102]  [ 51 76 107]  [ 46 71 102]]
 [[ 45 130 211]  [ 45 130 211]  [ 48 130 212] ...  [ 42 67 98]  [ 45 70 101]  [ 49 74 105]]
 ...
 [[102 53 21]  [101 51 18]  [111 59 22] ...  [ 28 17 11]  [ 31 16 9]  [ 33 16 9]]
 [[ 99 49 14]  [ 85 35 0]  [100 50 13] ...  [ 29 16 10]  [ 30 15 8]  [ 33 16 9]]
 [[ 93 45 7]  [ 91 46 7]  [ 93 47 11] ...  [ 29 16 10]  [ 36 19 12]  [ 39 20 14]]]