user3054329
user3054329

Reputation: 1

How do I cut the black things out of an image in pygame?

Hey I would like to cut out the black things of an image so that there is just the picture without black and then the programm should save the new image but i don't know how to do this :/ I just got how to display an image:

import pygame
import os
pygame.init()
surface = pygame.display.set_mode((500,500))
asurf = pygame.image.load(os.path.join("shot.png"))
asurf = pygame.transform.scale(asurf, (500, 500))
surface.blit(asurf,(0,0))
pygame.display.flip()

Upvotes: 0

Views: 400

Answers (2)

Marcus Møller
Marcus Møller

Reputation: 618

EDIT: Sorry, my initial answer was only related to transparency within in PyGame, not for saving images.

To do pixel modification, you would probably want to use another library such as PIL (Python Imaging Library).

See this thread if you want to give PIL a shot: PIL Best Way To Replace Color?

If you want to stick with PyGame for this, then you should look into pygame.surfarray: http://www.pygame.org/docs/tut/surfarray/SurfarrayIntro.html

EDIT2: Here's a quick snippet:

import pygame

# initialize pygame
pygame.init()
pygame.display.set_mode((500, 500))

# load image
image_surf = pygame.image.load('test.png',).convert_alpha()

# load pixel information from surface
image_pixels = pygame.surfarray.pixels3d(image_surf)

# create a copy for pixel manipulation
new_surf = image_surf.copy()

# loop through every pixel
i = 0
for x in range(len(image_pixels)):
    for y in range(len(image_pixels[0])):
        if image_pixels[x][y][0] == 0 and image_pixels[x][y][1] == 0 and image_pixels[x][y][2] == 0:
            # set transparency
            new_surf.set_at((x, y), pygame.Color(0, 0, 0, 0))

# save image
pygame.image.save(new_surf, "out.png")

OLD ANSWER: How to achieve transparency within in PyGame

You need to look-up set_colorkey(): http://www.pygame.org/docs/ref/surface.html#pygame.Surface.set_colorkey

If your image is already transparent, then you'd just need to load the image with .convert_alpha():

asurf = pygame.image.load(os.path.join("shot.png")).convert_alpha()

Even if you do not have transparency in your image, it's always a good idea to call .convert():

asurf = pygame.image.load(os.path.join("shot.png")).convert()

See this: (Link removed due to a 2-links-only limit)

Upvotes: 1

Or Halimi
Or Halimi

Reputation: 671

I know that pillow module got function that check for the pixel color. I saw someone load an image like a file, loop though its pixels and check if its a specific color.

Unlucky, i can't find it now. I link here the image color module in the pillow doc, i hope its will help you.

Upvotes: 0

Related Questions