how to indent and stack while loops in python?

Question:

I have a problem stacking while functions to make an algorithm that fills black an image except where it’s black within a 2d array the image
i want the algorithm to go along the columns anf fill black and when it encounters color it goes back reverse mode until he meet black again.
it should color the withe in the picture black here is my code :

the code : thecode

the result : theresult

i dont know why the indentation i = i+1 is not working. Help ?

could someone explain indentation please ?

Asked By: sonique

||

Answers:

The best I understand your requirement to be is to change the white (background) to black, or change any array value 240 and above to 1.
If so you don’t need all the loops, just change the value as you loop through each element if it’s greater or equal to 240

from PIL import Image
import numpy as np


def cleanw(t):
    i = 0
    while i < len(t):  # 682 is number of arrays elements in t array
        j = 0
        while j < len(t[i]):  # 1100 is the length of each element
            if t[i, j] >= 240:
                t[i, j] = 1
            j += 1
        i += 1


img = Image.open("sk.png")
t = np.array(img)
cleanw(t)
print(t)
img_out = Image.fromarray(t)
img_out.save('sk2.png')
img_out.show() 

Output (if interested)

[[1 1 1 ... 1 1 1]
 [1 1 1 ... 1 1 1]
 [1 1 1 ... 1 1 1]
 ...
 [1 1 1 ... 1 1 1]
 [1 1 1 ... 1 1 1]
 [1 1 1 ... 1 1 1]]

###———-Additional Information ———###
OK, being that the above code sample is your end requirement and answers the question ‘how to indent and stack while loops’, I’ll include this code sample which is a better way to achieve the element changes with numpy. Looping through each elelment is not necessary, you can just use the numpy indexing.

from PIL import Image
import numpy as np


img = Image.open("sk.png")
t = np.array(img)
# cleanw(t)
t[t >= 240] = 1   # Change all elements that are greater or equal to 240 to the value 1
print(t)
img_out = Image.fromarray(t)
img_out.save('sk2.png')
img_out.show()
Answered By: moken
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.