简体   繁体   中英

How to check pixel color with Pyglet?

I'm using Pyglet and trying to print the background color of the current position of the mouse. The script that launch the application is the following:

import pyglet

from pyglet.window import Window
from background import Background


window = Window(fullscreen=True)

game_batch = pyglet.graphics.Batch()

r = Background(batch=game_batch)

@window.event
def on_mouse_motion(x,y, dx, dy):
    print(x,y) # print current position
    #### ... but how to print pixel color (RGB) here? ####

@window.event
def on_draw():
    window.clear()
    game_batch.draw()


if __name__ == '__main__':
    pyglet.app.run()

The class Background.py is:

import pyglet

from physical_object import PhysicalObject

pyglet.resource.path = ['./resources']
pyglet.resource.reindex()

my_img = pyglet.resource.image('background.png')


class Background(PhysicalObject):
    def __init__(self, *args, **kwargs):
        super().__init__(img=my_img, *args, **kwargs)


Checking the docs, I've seen that OpenGL can be used to extract this color information, but I'm confused about how. Should I use OpenGL? Or there is a simpler way to access pixel color?

Thanks in advance.

Maybe you can take a look at this: Setting individual pixels in Pyglet

But in general, img.get_image_data() always returns all the pixels. Here's the documentation to this: https://pyglet.readthedocs.io/en/latest/modules/image/#pyglet.image.AbstractImage.get_image_data

With the ImageData object you can then use 'set_data' or 'get_data' to retrieve or set pixels.

I've tried the solution proposed by Hyalunar just adding the following method to class Background , which is called in every mouse motion event:

def check_position(self, x, y):
    img_data = road_img.get_region(x, y, 1, 1).get_image_data()
    width = img_data.width
    data = img_data.get_data('RGB', 3 * width)
    print(data[0] + ', ' + data[1] + ', ' + data[2])

And that solution works perfect!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM