#π Check if percentage of image is transparent
7 messages Β· Page 1 of 1 (latest)
@rancid pike
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
I'd count the number of pixels with a nonzero alpha channel value.
The fast way, if the image is big, might be to convert to a numpy or arrow array and use its array facilities.
You can make Pillow images from arrays, see https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.fromarrow and https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.fromarray
Both have examples of getting a numpy or pyarrow array from an image, since they're compatible, eg:
from PIL import Image
import numpy as np
im = Image.open("hopper.jpg")
a = np.asarray(im)
Given the above numpy array counting alpha pixels should be not too hard.
I'm suggesting numpy because it's designed for fast bulk compute, where Pillow pretty much only offers get-a-single-pixel calls, very slow for this kind of thing.
See: https://numpy.org/doc/stable/reference/arrays.html
@rancid pike
This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.