保存和读取带有透明通道的视频

保存带有透明通道的视频:

import os

import imageio
from rembg import remove as removBg,new_session
from PIL import Image
import numpy as np
import cv2
from tqdm import tqdm


class cls_rembg():
    def __init__(self,model_pth):
        self.session = new_session(model_pth)
    # 替换img_src 背景图路径为img_back_path,img_back_path == None 为透明
    # 输入图片为 pil image 输出为替换好的 pil image
    def remove_background(self,img_src,bgcolor = None,img_back_path = None,needRemoveBg = True):
        imgret_newbg = img_src
        output_png = img_src
        if needRemoveBg:
            if img_back_path is not None:
                output_png = removBg(data = img_src,session=self.session,alpha_matting_erode_size = 5)
                imgret_newbg = self.replace_background(output_png,img_back_path=img_back_path)

            elif bgcolor is not None:
                output_png = removBg(data = img_src,session=self.session,bgcolor = bgcolor,alpha_matting_erode_size = 5)

        imgret_nobg = output_png
        return imgret_newbg,imgret_nobg

if __name__ == '__main__':
    rembg = cls_rembg('u2net_human_seg.onnx')
    video_stream = cv2.VideoCapture("1.mp4")
    face_nobg =  'test_nobg.mov'
    #face_nobg = 'test_nobg.webm'
    face_newbg = 'test_newbg.mp4'
    video_writer = imageio.get_writer(face_nobg, format='FFMPEG', mode='I', codec='png', fps=30,
                                      ffmpeg_params=['-pix_fmt', 'rgba'])
    #video_writer = imageio.get_writer(face_nobg, format='FFMPEG', mode='I', codec='libvpx-vp9', fps=30)
    frames_nobg = []
    frames_newbg = []
    full_frames = []
    fps = video_stream.get(cv2.CAP_PROP_FPS)
    while True:
        still_reading, frame = video_stream.read()
        if not still_reading:
            video_stream.release()
            break
        full_frames.append(frame)

    back_color = (255, 255, 255, 0)
    if len(full_frames) > 0:
        for idx in tqdm(range(len(full_frames)), 'remove/replace background'):
            frame_face = Image.fromarray(cv2.cvtColor(full_frames[idx], cv2.COLOR_BGRA2RGBA))
            frame_newbg, frame_nobg = rembg.remove_background(frame_face, back_color, None)
            frames_nobg.append(frame_nobg)
            image = np.array(frame_nobg)

            # 确保图像的尺寸与第一个图像相同
            #if image.shape[:2] != (700, 700):
                #raise ValueError("All images should have the same dimensions.")

            # 将图像的 alpha 通道分离出来
            #alpha_channel = image[:, :, 3]

            # 将图像的 alpha 通道与 RGB 通道合并,得到 RGBA 图像
            #rgba_image = np.dstack((image[:, :, :3], alpha_channel))
            video_writer.append_data(image)

    video_writer.close()
    #if len(frames_nobg) > 0:
        #frames_nobg[0].save(face_nobg, save_all=True, append_images=frames_nobg, fps=float(fps))


保存带有透明通道的视频:

from moviepy.editor import VideoFileClip, CompositeVideoClip
from moviepy.video.io.ffmpeg_reader import FFMPEG_VideoReader
import imageio

zm_video_path = "test_nobg.mov"

if __name__ == '__main__':

    #video_stream = imageio.get_reader("test_nobg.mov", format='FFMPEG', fps=30,
    #                                  ffmpeg_params=['-pix_fmt', 'rgba'])
    video_stream = VideoFileClip('test_nobg.mov', has_mask=True).reader
    frames_nobg = []
    frames_newbg = []
    full_frames = []
    for num, frame in enumerate(video_stream.read_frame()):
        full_frames.append(frame)

    print('{}'.format(len(full_frames)))
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 MATLAB 中,要保存带有透明背景的图像,可以使用 `exportgraphics` 函数。首先,你需要确保你的图像有一个 alpha 通道,它指定了每个像素的不透明度。然后,你可以使用以下代码保存图像: ```matlab % 创建一张带有透明背景的图像 image = imread('input_image.png'); image_with_alpha = im2double(image); alpha_channel = create_alpha_channel(image_with_alpha); % 这里需要根据你的需求创建 alpha 通道 % 保存图像 output_image_filename = 'output_image.png'; exportgraphics(image_with_alpha, output_image_filename, 'Resolution', 300, 'BackgroundColor', 'none'); ``` 在上面的代码中,`imread` 函数用于读取输入图像。接下来,我们使用 `im2double` 函数将图像转换为 double 类型,以便进行后续处理。然后,你需要使用 `create_alpha_channel` 函数创建一个与图像大小相同的 alpha 通道。这个函数的实现取决于你想要的透明度模式。最后,我们使用 `exportgraphics` 函数将带有透明背景的图像保存为 PNG 格式,并将背景颜色设置为 `'none'`。 请注意,`exportgraphics` 函数需要 MATLAB R2020b 或更高版本才能使用。如果你的 MATLAB 版本较旧,你可以尝试使用 `print` 函数来保存图像: ```matlab % 保存图像 output_image_filename = 'output_image.png'; print('-dpng', '-r300', '-opengl', output_image_filename); ``` 这里,`'-opengl'` 选项用于确保图像保存为具有透明背景的 PNG 格式。你可以调整分辨率(`'-r300'`)和输出文件名(`output_image.png`)以适应你的需求。 希望这能帮到你!如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值