[英]PIL image to array (numpy array to array) - Python
我有一個.jpg圖像,我想轉換為Python數組,因為我實現了處理普通Python數組的處理例程。
似乎PIL圖像支持轉換為numpy數組,並且根據我編寫的文檔:
from PIL import Image
im = Image.open("D:\Prototype\Bikesgray.jpg")
im.show()
print(list(np.asarray(im)))
這將返回一個numpy數組列表。 另外,我試過了
list([list(x) for x in np.asarray(im)])
由於它失敗了,它什么都沒有返回。
如何從PIL轉換為數組,或者簡單地從numpy數組轉換為Python數組?
我強烈建議您使用Image
對象的tobytes
功能。 經過一些時間檢查后,這會更有效率。
def jpg_image_to_array(image_path):
"""
Loads JPEG image into 3D Numpy array of shape
(width, height, channels)
"""
with Image.open(image_path) as image:
im_arr = np.fromstring(image.tobytes(), dtype=np.uint8)
im_arr = im_arr.reshape((image.size[1], image.size[0], 3))
return im_arr
我在筆記本電腦上播放的時間顯示
In [76]: %timeit np.fromstring(im.tobytes(), dtype=np.uint8)
1000 loops, best of 3: 230 µs per loop
In [77]: %timeit np.array(im.getdata(), dtype=np.uint8)
10 loops, best of 3: 114 ms per loop
```
我認為你在尋找的是:
list(im.getdata())
或者,如果圖像太大而無法完全加載到內存中,那么類似的東西:
for pixel in iter(im.getdata()):
print pixel
來自PIL文檔 :
的GetData
im.getdata()=>序列
將圖像的內容作為包含像素值的序列對象返回。 序列對象被展平,因此第一行的值緊跟在第0行的值之后,依此類推。
請注意,此方法返回的序列對象是內部PIL數據類型,它僅支持某些序列操作,包括迭代和基本序列訪問。 要將其轉換為普通序列(例如用於打印),請使用list(im.getdata())。
根據zenpoy的回答 :
import Image
import numpy
def image2pixelarray(filepath):
"""
Parameters
----------
filepath : str
Path to an image file
Returns
-------
list
A list of lists which make it simple to access the greyscale value by
im[y][x]
"""
im = Image.open(filepath).convert('L')
(width, height) = im.size
greyscale_map = list(im.getdata())
greyscale_map = numpy.array(greyscale_map)
greyscale_map = greyscale_map.reshape((height, width))
return greyscale_map
我使用numpy.fromiter來反轉8灰度位圖,但沒有副作用的跡象
import Image
import numpy as np
im = Image.load('foo.jpg')
im = im.convert('L')
arr = np.fromiter(iter(im.getdata()), np.uint8)
arr.resize(im.height, im.width)
arr ^= 0xFF # invert
inverted_im = Image.fromarray(arr, mode='L')
inverted_im.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.