Python is zero-indexed
, i.e. if you have a list
such as:
l = [1, 4, 7, 3, 6]
and you want to iterate
through it with a while loop
(a for-loop
would be better but never mind), then you would have to loop
while
the index
is less than the length
of the list
- so the index
is never actually the length
of the list
, just up to 1
before.
The code for iterating
over the list
above would look something like:
i = 0
while i < len(l):
print(l[i])
i += 1
which would give you the output
of:
1
4
7
3
6
The same logic applies to your image
- which after all is essentially just a 2-dimensional
list
.
This means you need to correct the less than or equal
(<=
) comparators in your code to just less thans
(<
). Then your code should function how you would like it to.
So this would be the corrected code:
from PIL import Image
pix = newimage2.load()
print(newimage2.size)
print(" ")
whitevalues = 0
x = 0
while x < newimage2.width:
y = 0
while y < newimage2.height:
print(pix[x,y])
if pix[x,y] == (255,255,255):
whitevalues += 1
y += 1
x += 1
print(whitevalues)
However, as I mentioned at the start, a for-loop
would be better for this application as it will require fewer lines and is more Pythonic. So here is the code for a for-loop
which you may find useful:
from PIL import Image
pix = newimage2.load()
print(newimage2.size)
print(" ")
whitevalues = 0
for row in newimage2:
for col in row:
print(col)
if col == (255,255,255):
whitevalues += 1
print(whitevalues)
Or, if you wanted to be extremely pythonic, you could do this in a list-comprehension
:
whitevalues = sum([1 for r in pix for c in r if c == 1])