如何在沒有外部函式庫的情況下在 Python 中讀取和寫入像素 RGB 值?

Patricia Arquette
發布: 2024-10-17 21:11:30
原創
990 人瀏覽過

How to Read and Write Pixel RGB Values in Python Without External Libraries?

在Python 中讀取和寫入像素的RGB 值(無需外部庫)

雖然在Python 中獲取像素RGB 值通常涉及利用外部庫例如OpenCV 或scikit-image,可以直接使用Python 圖像庫(PIL) 執行此操作,無需額外下載。

擷取RGB 值:

  1. 使用PIL 的Image.open() 方法開啟影像:

    <code class="python">import PIL.Image as Image
    im = Image.open('image.jpg')</code>
    登入後複製
  2. 將影像的像素資料載入像素存取物件:
    <code class="python">pix = im.load()</code>
    登入後複製
  3. 使用像素座標存取各個像素值:
    <code class="python">print(pix[x, y])  # Outputs the RGB tuple of the pixel at (x, y)</code>
    登入後複製

設定RGB 值:

  1. 使用PIL 的Image.new() 方法取得空白畫布(新影像):
    <code class="python">new_im = Image.new('RGB', (width, height))</code>
    登入後複製
  2. <code class="python">new_pix = new_im.load()</code>
    登入後複製
    載入新影像的像素存取物件:
  3. <code class="python">new_pix[x, y] = (R, G, B)  # Sets the RGB tuple for the pixel at (x, y)</code>
    登入後複製
    設定特定像素值:
  4. <code class="python">new_im.save('output.jpg')</code>
    登入後複製
    保存修改後的圖像:

注意:

雖然此方法不需要外部庫,但與專用圖像處理庫相比,它在功能和圖像格式支援方面可能存在限制。如果需要更進階的操作,建議探索外部程式庫。

以上是如何在沒有外部函式庫的情況下在 Python 中讀取和寫入像素 RGB 值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!