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

วิธีใช้ scikit-learn แปลงภาพจาก RGB เป็น Grayscale ใน Python

scikit-learn (sklearn) ไลบรารีสำหรับ Machine Learning การแปลง color space ใช้เพื่อให้ได้ input ที่ดีกว่าสำหรับ operation อื่นๆ เช่น แยก hue, luminosity, saturation

RGB → Grayscale: ค่าพิกเซล = weighted sum ของ R, G, B

Y = 0.2125 R + 0.7154 G + 0.0721 B

น้ำหนักเหล่านี้มาจาก CRT phosphors ที่ตรงกับการรับรู้สีของมนุษย์มากกว่าน้ำหนักเท่ากัน

ตัวอย่าง

from skimage import io
import matplotlib.pyplot as plt
from skimage import data
from skimage.color import rgb2gray
from skimage import data
path = "path to puppy_1.JPG"
orig_img = io.imread(path)
grayscale_img = rgb2gray(orig_img)
fig, axes = plt.subplots(1, 2, figsize=(8, 4))
ax = axes.ravel()
ax[0].imshow(orig_img)
ax[0].set_title("Original image")
ax[1].imshow(grayscale_img, cmap=plt.cm.gray)
ax[1].set_title("Grayscale image")
fig.tight_layout()
plt.show()

ผลลัพธ์

วิธีใช้ scikit-learn แปลงภาพจาก RGB เป็น Grayscale ใน Python

คำอธิบาย

  • นำเข้าไลบรารี
  • กำหนดพาธภาพ
  • ใช้ 'imread' อ่านภาพ
  • ใช้ 'imshow' แสดงภาพ
  • ฟังก์ชัน 'rgb2gray' แปลง RGB → grayscale
  • matplotlib พล็อตภาพต้นฉบับและ grayscale
  • แสดงผล

หมายเหตุ: ใช้ scikit-image (skimage) ไม่ใช่ scikit-learn (sklearn)