问题
I'm using python 2.7, and I am currently working on a basic game in pyagme for my school work. I downloaded an image from google, and it has a background color and I know it's RGB. I remember that there is a method that makes the screen ignore this RGB for the picture (the picture will appear without the background color) but I don't remember it.
import pygame
WINDOW_WIDTH = 1200
WINDOW_LENGTH = 675
IMAGE = r'C:\Users\omero\Downloads\BattleField.jpg'
PISTOL_IMAGE = r'C:\Users\omero\Downloads\will.jpg'
RED = (255,0,0)
BLACK = (0,0,0)
WHITE = (255,255,255)
pygame.init()
size = (WINDOW_WIDTH, WINDOW_LENGTH)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Game")
clock = pygame.time.Clock()
img = pygame.image.load(IMAGE)
screen.blit(img, (0,0))
pygame.display.flip()
pistol_img = pygame.image.load(PISTOL_IMAGE)
colorkey = pistol_img.get_at((0,0))
screen.blit(pistol_img,(50,50))
pygame.display.flip()
finish = False
while not finish:
for event in pygame.event.get():
if event.type == pygame.QUIT:
finish = True
pygame.quit()
When I run the above I get the background color with pistol_img, how do I make the screen ignore it without editing the image?
回答1:
The white artifacts you can see in the picture are caused because the JPG format is a compressed format.
The compression is not lossless. This means the colors around the weapon are not exactly white (255, 255, 255). The color appear to be white for the human eye, but actually the color channels have a value lass than 255, but near to 255.
You can try to correct this manually. Ensure that format of the image has an alpha channel by pygame.Surface.convert_alpha(). Identify all the pixel, which have a red green and blue color channel above a certain threshold (e.g. 230). Change the color channels and the alpha channel of those pixels to (0, 0, 0, 0):
img = pygame.image.load(IMAGE).convert_alpha()
threshold = 230
for x in range(img.get_width()):
for y in range(img.get_height()):
color = img.get_at((x, y))
if color.r > threshold and color.g > threshold and color.b > threshold:
img.set_at((x, y), (0, 0, 0, 0))
Of course you are in danger to change pixels which you don't want to change to. If the weapon would have some very "bright" areas, then this areas my become transparent, too.
Note, an issue like this can be avoided by using a different image format like BMP or PNG.
With this formats the pixel can be stored lossless.
You can try to "photo shop" the image. Manually change the pixel around the weapon and store the image with a different format.
来源:https://stackoverflow.com/questions/55648488/how-do-i-make-the-screen-ignore-the-background-color-of-some-image