PyGame或Moviepy以透明方式显示视频

2024-09-10 06:32:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个非常奇怪的情况,但我会尽力尽我所能解释一切。所以我用PyGame编写了一个游戏。我用moviepy在地面上播放视频。现在我正在做一个战斗屏幕,我想动画的攻击。我将快速显示屏幕截图

Heres the screen of the combat

当点击“火球”时,我想显示一个火球。视频本身是透明的,但它用白色填充

例如,我之前用于显示剪切场景的代码如下:

video = VideoFileClip('assets/Attacks/Frantz/fireball.webm')
video.preview()

当它播放视频时,看起来如下所示:

Here

我的初始文件是一个gif,我将其转换为mp4。我发现mp4不支持alpha/透明度,我尝试使用gif将video = VideoFileClip('assets/Attacks/Frantz/fireball.mp4')替换为video = VideoFileClip('assets/Attacks/Frantz/fireball.gif') 但同样的事情也发生在白色背景上(是的,gif有100%的透明度) 我有点不知道该怎么办。我是否应该尝试其他文件格式,如果是,我如何删除透明度,但我认为我需要更改代码中的某些内容,以便能够实际使用gif或其他格式

这是gif的文件

我知道我的问题很奇怪,但这是一个学校项目,我非常感谢你的帮助


Tags: 文件代码视频屏幕videogifmp4透明度
1条回答
网友
1楼 · 发布于 2024-09-10 06:32:10

电影不是你想要的。你想要的是一个动画精灵。动画精灵由许多不同的精灵组成,这些精灵在连续帧中显示。这些精灵的来源可以是精灵表、动画GIF或位图列表

关于这个话题有各种各样的问题和答案。例如:


由于GIF不是透明的,因此必须使用^{}设置透明颜色的颜色键:

pygameImage.set_colorkey((0, 0, 0))

例如:

import pygame
from PIL import Image, ImageSequence

def pilImageToSurface(pilImage):
    return pygame.image.fromstring(
        pilImage.tobytes(), pilImage.size, pilImage.mode).convert()

def pilImageToSurface(pilImage):
    return pygame.image.fromstring(
        pilImage.tobytes(), pilImage.size, pilImage.mode).convert()

def loadGIF(filename):
    pilImage = Image.open(filename)
    frames = []
    if pilImage.format == 'GIF' and pilImage.is_animated:
        for frame in ImageSequence.Iterator(pilImage):
            pygameImage = pilImageToSurface(frame.convert('RGB'))
            pygameImage.set_colorkey((0, 0, 0))
            frames.append(pygameImage)
    else:
        frames.append(pilImageToSurface(pilImage))
    return frames
 
pygame.init()
window = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()

background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:#
    pygame.draw.rect(background, color, rect)

gifFrameList = loadGIF('fire.gif')
currentFrame = 0

run = True
while run:
    clock.tick(20)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.blit(background, (0, 0))

    rect = gifFrameList[currentFrame].get_rect(center = (250, 250))
    window.blit(gifFrameList[currentFrame], rect)
    currentFrame = (currentFrame + 1) % len(gifFrameList)
    
    pygame.display.flip()

pygame.quit()
exit()

相关问题 更多 >