PIL 的 getpixel 似乎略慢

由於想針對影像做處理,使用 loop 去拿image 裡的pixel 使用 image.getpixel 似乎太沒有效率,於是使用 numpy.asarray() 把 PIL image object 轉成 array.

使用的範例圖片 width: 921, height 1001, 服用下面的 code 後:

import PIL
import numpy
from PIL import Image
im = Image.open('U_51234.bmp')
data = numpy.asarray(im)
print("shape:", data.shape)
print("100,150:",data[100,150])
print("100,150:",data[100][150])

取得 shape: (1001, 921)

所以是先 h 再 w, 如果要直接 access array 需要先放 y axis ,再使用 x axis, 與原先的 getpixel(x,y) 順序會相反。


Convert between PIL image and NumPy ndarray

image = Image.open(“max-demo.jpg”)   # image is a PIL image 
array = numpy.array(image)          # array is a numpy array 
image2 = Image.fromarray(array)   # image2 is a PIL image

Convert between PIL image and PyOpenCV matrix

image = Image.open(“max-demo.jpg”)                  # image is a PIL image
mat = pyopencv.Mat.from_pil_image(image)  # mat is a PyOpenCV matrix 
image2 = mat.to_pil_image()                        # image2 is a PIL image

Convert between OpenCV image and NumPy ndarray

cimg = cv.LoadImage("max-demo.jpg", cv.CV_LOAD_IMAGE_COLOR)   # cimg is a OpenCV image 
pimg = Image.fromstring("RGB", cv.GetSize(cimg), cimg.tostring())  # pimg is a PIL image 
array = numpy.array(pimg)     # array is a numpy array 
pimg2 = cv.fromarray(array)    # pimg2 is a OpenCV image

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *