Helpman88
Helpman88

Reputation: 3

algorithm for converting images does not work

i'm new in the programingworld and I try to teach programing myself and I wanted to start with at python with an algorythm, where you can put photos, this has to be a black-and-white phote and the program will order them into greyscales and the greyscales are then divided into different dollar signs based on the strength. So I hope you understood what I am up to. Now here is the Code.

def open_image(filename):
...


def main():
intervals = [[0, 70], [71, 140], [141, 190], [191, 255]]
dollar_pixels = ["   ", " $ ", "$ $", "$$$"]
assert len(intervals) == len(dollar_pixels)

with open_image("donald.jpg") as image:
    for count, pixel in enumerate(image.get_pixels()):
        for (lower_limit, upper_limit), dollar_pixel in zip(
            intervals, dollar_pixels
        ):
            if lower_limit <= pixel <= upper_limit:
                print(dollar_pixel)
                break
        else:
            raise ValueError(f"pixel {pixel!r} not in any interval")

        if count and count % image.get_width() == 0:
            print("\n")


if __name__ == "__main__":
main()

And this is the error message:

Microsoft Windows [Version 10.0.19043.1237]
(c) Microsoft Corporation. Alle Rechte vorbehalten.

Traceback (most recent call last):
File "c:/Users/User/OneDrive/Desktop/folder1/donald.py", line 29, in <module>
main()
File "c:/Users/User/OneDrive/Desktop/folder1/donald.py", line 13, in main
with open_image("donald.jpg",) as image:
AttributeError: __enter__

I made there 3 points after def open_image(filename), because I don't realy know, what I was supossed to write and I didn't find a module to read the Photos. I hope you guys can give me an respectful answer, where you will describe every single errors of mine, things I forgot to write and the solution for all these things.

Take care Helpman88

Upvotes: 0

Views: 27

Answers (1)

Ulises Bussi
Ulises Bussi

Reputation: 1725

it's seem a problem with context manager (the thing that you are trying to do with " with open_image("donald.jpg") as image: " the most simple way to solve this is to assign the returning object of get_image as a variable:

    image = get_image(filename)
    for count, pixel in enumerate(image.get_pixels()):
        ...

here you have more information about context managers if you want to solve your problem this way:

https://book.pythontips.com/en/latest/context_managers.html

Upvotes: 1

Related Questions