![](/img/trans.png)
[英]How do i make a function that iterate over all the pixels in an image to find a specified colour using numpy
[英]How can I get the pixels matrix of an image without using numpy?
我想找到一種無需使用numpy
即可獲取像素矩陣的方法。 我知道與代碼一起使用
from PIL import Image
import numpty as np
img = Image.open('example.png', 'r')
pixels = np.array(img)
pixels
獲取圖像的像素矩陣。 不過,我想找到不使用方式numpy
,以獲得像素的圖像,而無需使用包numpy
。 提前致謝!
您可以使用Image
方法getdata(band=None)
或getdata(band=None)
getpixel(xy)
。
In [1]: from PIL import Image
In [2]: im = Image.open('block.png', 'r')
In [3]: data = list(im.getdata())
In [4]: data[:20]
Out[4]:
[(0, 0, 0),
(0, 0, 0),
(0, 0, 0),
(0, 0, 0),
(0, 0, 0),
(0, 0, 0),
(0, 0, 0),
(0, 0, 0),
(0, 0, 0),
(0, 0, 0),
(0, 0, 0),
(144, 33, 33),
(144, 33, 33),
(144, 33, 33),
(144, 33, 33),
(255, 255, 255),
(255, 255, 255),
(255, 255, 255),
(255, 255, 255),
(0, 0, 0)]
In [5]: pxl = im.getpixel((1, 1))
In [6]: pxl
Out[6]: (144, 33, 33)
要將getdata()
返回的序列轉換為列表列表,可以使用列表理解:
In [61]: data2d = [data[i:i+im.width] for i in range(0, len(data), im.width)]
In [62]: data2d[0] # row 0
Out[62]:
[(0, 0, 0),
(0, 0, 0),
(0, 0, 0),
(0, 0, 0),
(0, 0, 0),
(0, 0, 0),
(0, 0, 0),
(0, 0, 0),
(0, 0, 0),
(0, 0, 0)]
In [63]: data2d[1] # row 1
Out[63]:
[(0, 0, 0),
(144, 33, 33),
(144, 33, 33),
(144, 33, 33),
(144, 33, 33),
(255, 255, 255),
(255, 255, 255),
(255, 255, 255),
(255, 255, 255),
(0, 0, 0)]
In [64]: data2d[1][1]
Out[64]: (144, 33, 33)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.