Reputation: 31
I have a question to do with the Python module pygame.
I want to change the hue of an image for a sprite, like applying a filter to the image. I have seen many posts concerning changing specific pixels from one color to another, although this is not what I want to do. I want to do something similar to what can be done in simple photo editing software such as paint.net, changing the overall color of an image. I could of course change the hue of the image in a photo editing software, but this would lead to lots of images needing to be made and loaded and managed, it would quickly become very tedious. I am hoping that there is some sort of way to change the hue of an image in pygame.
Upvotes: 2
Views: 3323
Reputation: 4719
The hue of each pixel in an image can be shifted using
PixelArray
to
iterate over each pixel,
Surface.unmap_rgb
to get a Color object from each pixel, and
Color.hsla
to do the
hue shift.
# Get the pixels
pixels = PixelArray(surface)
# Iterate over every pixel
for x in range(surface.get_width()):
for y in range(surface.get_height()):
# Turn the pixel data into an RGB tuple
rgb = surface.unmap_rgb(pixels[x][y])
# Get a new color object using the RGB tuple and convert to HSLA
color = Color(*rgb)
h, s, l, a = color.hsla
# Add 120 to the hue (or however much you want) and wrap to under 360
color.hsla = (int(h) + 120) % 360, int(s), int(l), int(a)
# Assign directly to the pixel
pixels[x][y] = color
# The old way of closing a PixelArray object
del pixels
If the surface is small, this could be run in real time. However, it would be better to run once at load time, especially if the surface is large.
Upvotes: 0
Reputation: 1
'''
Original post https://www.reddit.com/r/pygame/comments/hprkpr/how_to_change_the_color_of_an_image_in_pygame/
'''
blue_rgb = (0,0,255) red_rgb = (255,0,0) img =
pygame.image.load("sky_picture.png") # loads the picture from the path
given var = pygame.PixelArray(img)
# var.replace(([Colour you want to replace]), [Colour you want]) var.replace((blue_rgb), (red_rgb)) # replaces all blue in the picture
to red del var
"""
if the picture has some unchanged pixels left it's probably because they are not EXACTLY the rgb given for example (254,0,0) is not
(255,0,0) and won't be changed (to fix this you will have to calculate
the approx number ot just change the main picture)
"""
# I also uploaded this to grepper
Upvotes: 0
Reputation: 277
You can do this with Python PIL. Take a look at this question and answer, and especially the original question and answer that they link to:
Changing the color of an image based on RGB value
Upvotes: 1