py5coding / py5generator

Meta-programming project that creates the py5 library code.
https://py5coding.org/
GNU General Public License v3.0
52 stars 13 forks source link

Unable to change pixels' colors on image created with py5.create_image() #52

Closed sahver closed 2 years ago

sahver commented 2 years ago

Hi,

I am trying to change color of pixels of an image created with py5.create_image(), but for some reason I only get blacks or no image at all after changing the pixel values.

I am using the following code borrowed from the documentation to keep it simple:

class Test(Sketch):

    def settings(self):
        self.size(800, 800)

    def setup(self):
        img = self.create_image(66, 66, self.RGB)
        img.load_pixels()
        for i in range(0, len(img.pixels)):
            img.pixels[i] = self.color(0, 90, 102)

        img.update_pixels()
        self.image(img, 17, 17)
        self.image(img, 34, 34)

    def draw(self):
        pass

Test().run_sketch()

The result of this is two black squares: Screenshot 2021-12-07 172038

If I change the image type to ARGB, then I don't even get the black squares, just empty background.

I installed py5 to a new anaconda env with the provided py5_environment.yml as per documentation. I am running py5 0.6.0a2 on Windows 10.

Any ideas what's going on?

hx2A commented 2 years ago

It seems you have found a bug, and a foolish one at that. This will be fixed in the next release.

Until then, I will present some alternatives.

First, please give np_pixels a try:

http://py5.ixora.io/reference/sketch_np_pixels.html

You can interact with the image pixels using a 3 channel numpy array, much like you would with any other Python image library. You won't need for loops so it will be much faster. I never noticed this bug before because I never use the pixels array. np_pixels is nicer to work with.

You mentioned color gradients in the first version of this issue (which arrived by email), and it happens the create_image_from_numpy() example does exactly that:

http://py5.ixora.io/reference/sketch_create_image_from_numpy.html

If by chance neither of those options meets your needs or you prefer to use the pixel array, you can bypass the Python bug and access the Java object directly with this:

img._instance.pixels[i] = self.color(0, 90, 102)

Thanks for reporting this and for giving py5 a try!

sahver commented 2 years ago

Thank you for a prompt reply and for proposing alternatives. I went with _instance for now, this seemed easier for what I was looking for. Thank you for working on the project!

hx2A commented 2 years ago

Fixed. Thanks again for the bug report!

Next release will go out around the end of December or early January.