在Python中,可以使用Pillow庫或OpenCV庫來讀取和寫入PNG圖片的像素值。以下是兩種方法的詳細說明:
1. 使用Pillow庫
Pillow是Python中常用的圖像處理庫,支持多種圖像格式,包括PNG。
讀取像素值
from PIL import Image
img = Image.open('example.png')
# 獲取像素值
pixels = img.load()
# 讀取某個像素的值(坐標為x, y)
x, y = 100, 100
pixel_value = pixels[x, y]
print(pixel_value)? # 輸出像素值(RGB或RGBA)
寫入像素值
from PIL import Image
img = Image.open('example.png')
pixels = img.load()
# 修改某個像素的值(坐標為x, y)
x, y = 100, 100
pixels[x, y] = (255, 0, 0)? # 設置為紅色
# 保存修改后的圖片
img.save('modified.png')
2. 使用OpenCV庫
OpenCV是一個強大的計算機視覺庫,也支持PNG圖像的讀寫。
讀取像素值
import cv2
# 讀取PNG圖片
img = cv2.imread('example.png', cv2.IMREAD_UNCHANGED)? # 保留Alpha通道
# 讀取某個像素的值(坐標為y, x)
y, x = 100, 100
pixel_value = img[y, x]
print(pixel_value)? # 輸出像素值(BGR或BGRA)
寫入像素值
import cv2
# 讀取PNG圖片
img = cv2.imread('example.png', cv2.IMREAD_UNCHANGED)
# 修改某個像素的值(坐標為y, x)
y, x = 100, 100
# 安全的像素寫入方式(確保通道數匹配)
if len(img[y, x]) == 3:? # 3通道圖像
??? img[y, x] = [0, 0, 255]
elif len(img[y, x]) == 4:? # 4通道圖像(帶Alpha)
??? img[y, x] = [0, 0, 255, 255]? # 添加Alpha通道值
# 保存修改后的圖片
cv2.imwrite('modified.png', img)
注意事項
- ?坐標順序?:Pillow使用(x, y),而OpenCV使用(y, x)。
- ?顏色通道?:Pillow默認使用RGB,OpenCV默認使用BGR。
- ?Alpha通道?:PNG可能包含透明度通道(Alpha),處理時需注意。