Вопрос

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
Это было полезно?

Решение

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.

Другие советы

You can get individual pixels on image surfaces by using theget_atmethod of Pygame surfaces - as inmouse_c.get_at((0,0)).

This is strictly what you are asking for -- but it won't suit any real world needs, as it is extremely, and I am saying extremely, slow to process all pixels of an image calling just this.

You could take the image buffer withget_bufferand interpret the data there, raw, or pass the buffer along to a function written in native code to get some speed.

Still, if your goal is to replace a color by another in real time you can resort to use indexed images - that way, each image will have a color table, you just modify,say, the color number 10 to be 0,0,255, and as you render the image, all occurrences of that color become blue. This is fast -- not as efficient as back in the 8 bit video-games time when this was done by hardware -- but it will be orders of magnitude faster any substitutions you try to make in pure Python code.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top