fast way to get and set pixel color in pygame

fast way to get and set pixel color in pygame

By : Shannon Houchins
Date : November 22 2020, 10:31 AM
around this issue I am working on a simple project using pygame and I need to get and set pixel colors. Using pygame.get_at(()) and pygame.set_at(()) is VERY slow. , C++ SetPixel and GetPixel function
Part of window.h library
code :
  _In_  HDC hdc,
  _In_  int X,
  _In_  int Y,
  _In_  COLORREF crColor
  _In_  HDC hdc,
  _In_  int nXPos,
  _In_  int nYPos
Uint32 rawpixel = getpixel(surface, x, y);
Uint8 red, green, blue;

SDL_GetRGB(rawpixel, surface->format, &red, &green, &blue);
void setpixel(SDL_Surface *screen, int x, int y, Uint8 r, Uint8 g, Uint8 b)
    Uint32 *pixmem32;
    Uint32 colour;  

    colour = SDL_MapRGB( screen->format, r, g, b );

    pixmem32 = (Uint32*) screen->pixels  + y + x;
    *pixmem32 = colour;

Share : facebook icon twitter icon
Getting pixel color at location with pygame

Getting pixel color at location with pygame

By : keshav murthy
Date : March 29 2020, 07:55 AM
Hope this helps http://www.pygame.org/docs/ref/surface.html#Surface.get_at
Surface.get_at((x, y)): return Color
how to get the color value of a pixel in pygame?

how to get the color value of a pixel in pygame?

By : David Alanís
Date : March 29 2020, 07:55 AM
it should still fix some issue I want to get the color value of a pixel. I have read something about a function called "pygame.Surface.get_at()". But when I use this function i get this error: , You have two problems here:
code :
.get_at((300, 200))
screen = pygame.display.set_mode((150, 50))
screen.get_at((300, 200))
Pygame get color of pixel where cursor is located

Pygame get color of pixel where cursor is located

By : vonJanne
Date : March 29 2020, 07:55 AM
should help you out If the surface of the screen created with pygame.display.set_mode is surface then you can do this:
code :
color = surface.get_at(pygame.mouse.get_pos()) # get the color of pixel at mouse position
How to get color of each pixel on a screen in PyGame

How to get color of each pixel on a screen in PyGame

By : Yash1331
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , .get_at is a instance function method (see Method Objects) of pygame.Surface. So it has to be called on an instance of pygame.Surface. screen is the Surface object, which represents the window. So it has to be:
Pixels.append(pygame.Surface.get_at((i, j)))
code :
Pixels.append(screen.get_at((i, j)))
Pixels.append(pygame.Surface.get_at(screen, (i, j)))
How to get a pixel color outside of screen in pygame?

How to get a pixel color outside of screen in pygame?

By : Nikon95
Date : March 29 2020, 07:55 AM
should help you out Here's a stand-alone example that tracks the position of the view/camera on a larger background.
code :
import pygame
W = 600
H = 400
# generate repeated KEYDOWN events when a key is held
pygame.key.set_repeat(500, 50)  
screen = pygame.display.set_mode([W, H])

# image = pygame.image.load('huge_bkgnd.png').convert_alpha()

#create a large bkgnd image
bkgnd = pygame.Surface((W*10, H*10))
# draw a rainbow on the bkgnd surface
colours = ["red", "orange", "yellow", "green", "lightblue1", "blue", "purple"]
bar_width = bkgnd.get_width() // (10 * len(colours))
for x in range(0, bkgnd.get_width() // bar_width):
    rect = [x*bar_width, 0, bar_width, bkgnd.get_height()]
    bkgnd.fill(pygame.Color(colours[x % len(colours)]), rect)

position = [0, 0]
clock = pygame.time.Clock() #for limiting FPS
finished = False
while not finished:
    for event in pygame.event.get():
            if event.type == pygame.QUIT:
                finished = True
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    position[0] -= 100
                if event.key == pygame.K_RIGHT:
                    position[0] += 100
                if event.key == pygame.K_UP:
                    position[1] -= 100
                if event.key == pygame.K_DOWN:
                    position[1] += 100
                # for all key movement clamp position to size of background
                position[0] = max(0, min(position[0], bkgnd.get_width() - W))
                position[1] = max(0, min(position[1], bkgnd.get_height() - H))
                    x = position[0] + W*2  # just look at what's to the right
                    y = position[1]
                    print(f"At {position}: Heading for ({x},{y}) {bkgnd.get_at((x, y))}")
                except IndexError:
                    print(f"Heading for the edge! {bkgnd.get_width() - position[0]} to go!")
    # copy bkgnd to screen
    view_rect = (*position, W, H)
    screen.blit(bkgnd.subsurface(view_rect), (0,0))
    # update the screen
    clock.tick(60)  # limit FPS
Related Posts Related Posts :
  • pretty printing numpy ndarrays using unicode characters
  • Frequent pattern mining in Python
  • How can I make a set of functions that can be used synchronously as well as asynchronously?
  • Convert one dice roll to two dice roll
  • count occourrence in a list
  • Writing an If condition to filter out the first word
  • to read file and compare column in python
  • Install python-numpy in the Virtualenv environment
  • `.select_by_visible_text()` is failed to select element?
  • Unable to send data multiple requests in a single connection — socket error
  • Pandas HDFStore unload dataframe from memory
  • Creating a custom admin view
  • How do you get the user role of the currently logged in user in Ckan?
  • Speed up Numpy Meshgrid Command
  • Python error - name lengths
  • appending text to a global variable
  • Python Mistake - Number of letters in name
  • Searching for a sequence in a text
  • Testing logging output with pytest
  • How do I change my default working directory for Python (Anaconda) on VSCode?
  • .lower() for x in list, not working, but works in another scenario
  • Program gives error "List indices must not be string"
  • pyqt: Memory Usage
  • Confused about classes in Learn Python the Hard Way ex43?
  • Extracting unrecognized information from many CSV files
  • How do I connect to Postgresql server from Python?
  • Append rows to a pandas DataFrame without making a new copy
  • Scrapy: Importing a package from the project that's not in the same directory
  • launching Excel application using Python to view the CSV file , but CSV file is opening in read mode and cant view the d
  • Making a list in user-defined functions
  • Pyserial microcontroller to host communication
  • Plotting a line in between subplots
  • function not returning value. Error "NameError: name 'urlss' is not defined"
  • How to perform cartesian product with Tensorflow?
  • Multiple independent random number streams from single seed
  • I Need a simple and short python3 code that count secounds in a background process
  • No module named constants
  • from django 1.4 to django 1.5- argument 'verify_exists' what s replacement?
  • Slash replacement inside a raw string
  • Reordering columns/rows of a pivot_table?
  • MySQLdb.cursors.Cursor.execute does not work
  • Python module being reimported when imported at different places
  • Is the Session object from Python's Requests library thread safe?
  • Python Regex: Finding First and Last Names
  • Order by selection in List view of OpenERP 7.0
  • Reading input values in ipython notebook
  • List of dictionaries - how to read a specific value in a dictionary
  • writing os.system output to file
  • Create dictionary from points list and multiple attribute lists
  • How to write a table line by line with for loop
  • Map projection and forced interpolation
  • Django FBV's "render_to_response" equivalent in Class-Based-View?
  • Paramiko raises "SFTPError: Garbage packet received"
  • python pandas operations on columns
  • python list appending is not working
  • Speeding up matplotlib scatter plots
  • For each element of the list find closest date from a different list
  • How to prepend new rows at the beginning of an existing csv file?
  • how to make database robust to process kills with sqlite postgress and sqlalchemy?
  • finding a set of ranges that a number fall in
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org