Search code examples
pythoncolorspygamepalettecolor-palette

Python (pygame): Get image color information?


My end goal is to find a color in an image (in this case white) and replace it with another color (based on certain circumstances). So, as a certain variable changes the white is replaced with a specific color.

However, to get there I'm currently just playing with images (using tutorials ..etc). I'm trying to use the below code to print the color palette of an image. My understanding is the colors are a "tuple" of 3 integer representing RGB. 0 = darkest, 255 = white. So, the image I'm testing is a black and white image. I'm expecting something like "(0,0,0),(255,255,255)". So, I figured if I could get this far, then I could write a code to replace the "(255,255,255)" with the appropriate color.

I mentioned the end goal because I'm very aware that my approach might not be the best, and that perhaps someone has a better way I can go about this. If not, I'd at least like to be able to print a string referencing the colors an image contains. The "NOFRAME" was a great piece of advice I found on this site, as I'm not actually "using" the images/graphics - just using their attributes.

image1=r"C:\Python27\Lib\site-packages\pygame\examples\data\image1.jpg"
image2=r"C:\Python27\Lib\site-packages\pygame\examples\data\image2.png"

import pygame, sys
from pygame.locals import *

pygame.init()

pygame.display.set_mode((1,1), pygame.NOFRAME)

background = pygame.image.load(image1).convert()
mouse_c=pygame.image.load(image2).convert_alpha()

colorpal = pygame.Surface.get_palette(mouse_c)

print colorpal

Solution

  • What you want to do is going to require a lot of pixel level work, so I recommend that you use a pygame.PixelArray object for direct pixel access of the surface(s).

    For what you specifically want to do, it sounds like you could use the pygame.PixelArray.replace() method.