且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何让屏幕忽略某些图像的背景颜色?

更新时间:2023-01-27 11:47:29

您在图片中看到的白色伪影是由于 JPG 格式是压缩格式.
压缩不是无损的.这意味着武器周围的颜色并不完全是白色(255、255、255).颜色对于人眼来说看起来是白色的,但实际上颜色通道的值小于 255,但接近 255.

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.

您可以尝试手动更正此问题.通过 确保图像格式具有 Alpha 通道pygame.Surface.convert_alpha().识别所有像素,其具有高于特定阈值(例如 230)的红绿蓝颜色通道.将这些像素的颜色通道和 Alpha 通道更改为 (0, 0, 0, 0):

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.

请注意,可以通过使用不同的图像格式(例如 BMP)来避免此类问题或 PNG.
使用这种格式,可以无损地存储像素.你可以试试照相馆"图片.手动更改武器周围的像素并以不同格式存储图像.

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.