7
\$\begingroup\$

So I have recently tried to load an image and save it, but remove all of a certain color. I'm running the program and it is running really slow, is there a more efficient way to edit an image? My code is pasted below, or at least all that is relevant.

for x in range(50):
    im = pygame.image.load("horse%s.bmp") % (x)
    im.set_colorkey(im.get_at((0, 0)))
    surf = pygame.Surface((im.get_size(), pygame.SRCALPHA)
    surf.blit(im, (0, 0))
    pygame.image.save(surf, "horse%s.png") % (x)
\$\endgroup\$
0

1 Answer 1

5
\$\begingroup\$

You have a bug:

((im.get_size(), pygame.SRCALPHA)

You have one too many ('s.


Where did the number 50 come from in the range call?

Don't use magic numbers; set and use a variable, probably called picture_amount.


When you are using string formatting to put the number x into the image name string, you should be using %d or %i because those are for signed decimal (base 10) integers; %s is used for strings, which x is not.


After scrolling through some pygame documentation, your method for clearing all is a very good one for pygame. I am assuming that the excessive slowness is coming from having to paint the image to a surface every time.

A faster way to do this would probably be to use an image editing library so that you don't have to paint the image every time; you'd edit the image in the background.

I sifted through the PIL python imaging library and came across a convenient method call image.eval. This method will iterate through every pixel in an image, call a function (passed via argument) passing in the pixel information, and reset the pixel value based on the function output.

This may or may not be slower than what you are already doing.


Putting it all together:

from PIL import Image

for x in range(image_amount):
    im = Image.open("horse%d.bmp") % (x)
    Image.eval(im, lamda pix: 0 if p == im.getpixel((0,0))) # Sets the pixel value to 0... change this if you want.
    Image.save("horse%d", "PNG") % (x) # This could raise an IOException

I could not test this code at the time so if you see any errors, let me know.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.