I'd like to find a way of getting the pixels matrix without using numpy
. I'm aware that using with the code
from PIL import Image
import numpty as np
img = Image.open('example.png', 'r')
pixels = np.array(img)
pixels
get the pixels matrix of the image. However, I'd like to find a way without using numpy
to get the pixels image without using the package numpy
. Thanks in advance!
You can use the Image
methods getdata(band=None)
or 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)
To convert the sequence returned by getdata()
to a list of lists, you can use a list comprehension:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.