Reputation: 1258
I need all RGBA values of an image in a list. I can use getpixel()
function but I have to iterate for all pixels which is my aim and it does very slow. I need to do this in a few seconds.
This is my current code:
imgobj = Image.open('x.png')
pixels = imgobj.convert('RGBA')
lofpixels = []
w = 1920
h = 1080
for i in range(w):
for j in range(h):
r,g,b,a = pixels.getpixel((i,j))
lofpixels.append(r)
lofpixels.append(g)
lofpixels.append(b)
lofpixels.append(a)
Any suggestions? Thanks.
Upvotes: 1
Views: 8572
Reputation: 714
imgobj.getdata()
will give you a sequence of (red, green, blue, alpha)
tuples pretty quickly. (Docs here.)
Not sure what your use case is here, since it looks like you're just making one big flat array with all your reds, greens, blues and alphas jumbled together, but I suppose you could do something like this to get the same result:
imgobj = Image.open('x.png')
pixels = imgobj.convert('RGBA')
data = imgobj.getdata()
lofpixels = []
for pixel in data:
lofpixels.extend(pixel)
You also could get a count of each unique pixel value with collections.Counter
(docs here), for example:
imgobj = Image.open('x.png')
pixels = imgobj.convert('RGBA')
data = imgobj.getdata()
counts = collections.Counter(data)
print(counts[(0, 0, 0, 255)]) # or some other value
Upvotes: 2