亲宝软件园·资讯

展开

Python人像分割

学术菜鸟小晨 人气:0

一、原始视频截图

import cv2
cap=cv2.VideoCapture(r"【小仙若】shake it !冬日也要活力满满! (P1. shake it).mp4")
ret,frame=cap.read()
i =0
timeF=3
j=0
num=0
while 1:
  i=i+1
  if (i%timeF==0):
    j=j+1
    cv2.imwrite("./pictures/"+str(num)+".jpg",frame)
    num+=1
    print("save image:",i)
  ret,frame=cap.read()
 
  

二、提取人像

# -*- coding:utf-8 -*-
import cv2
import base64
import numpy as np
import os
from aip import AipBodyAnalysis
import time
import random
 
APP_ID = '25365416'
API_KEY = 'pS5cVzzw2iBfLY6MKRhUE4cw'
SECRET_KEY = '×××××××××××××××××××××××××'
 
client = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY)
# 保存图像分割后的路径
path = './mask_img/'
# os.listdir  列出保存到图片名称
pics = os.listdir('./pictures')
print(pics)
for im in pics:
    # 按顺序构造出图片路径
    img = os.path.join("./pictures",im)
    img1 = cv2.imread(img)
    height, width, _ = img1.shape
    # print(height, width)
    # 二进制方式读取图片
    with open(img, 'rb') as fp:
        img_info = fp.read()
 
 
    # 设置只返回前景   也就是分割出来的人像
    res = client.bodySeg(img_info)
    seg_res = client.bodySeg(img_info)
    labelmap = base64.b64decode(seg_res['foreground'])
    file = open('./he/'+im.split(".")[0]+'.png','wb')
    file.write(labelmap)
    file.close()
 
    print('======== 图像分割完成 ========')

三、和背景图合并

import cv2
import os
from PIL import Image
import numpy as np
 
 
background='1.jpg'
def blend_images(fore_image, base_image):
    """
    将抠出的人物图像换背景
    fore_image: 前景图片,抠出的人物图片
    base_image: 背景图片
    """
    # 读入图片
    base_image = Image.open(base_image).convert('RGB')
    fore_image = Image.open(fore_image).resize(base_image.size)
 
    # 图片加权合成
    scope_map = np.array(fore_image)[:,:,-1] / 255
    scope_map = scope_map[:,:,np.newaxis]
    scope_map = np.repeat(scope_map, repeats=3, axis=2)
    res_image = np.multiply(scope_map, np.array(fore_image)[:,:,:3]) + np.multiply((1-scope_map), np.array(base_image))
    
    #保存图片
    res_image = Image.fromarray(np.uint8(res_image))
    res_image.save(os.path.join('./he/',im))
    #cv2.imwrite(os.path.join(path1,im), result)
# os.listdir  列出保存到图片名称
 
pics = os.listdir('./he1/')
print(pics)
for im in pics:
    img='./he1/'+im
    blend_images(img, background)

四、合成视频

我的背景图尺寸是3840×2160

# 图片合成视频
import cv2
import os
pics = os.listdir('./he/')
fourcc = cv2.VideoWriter_fourcc('X','V','I','D')
# 保存格式,参数分别为filename,编码器,帧率,尺寸
out=cv2.VideoWriter("2.avi",fourcc,10,(3840,2160))
print(pics)
for im in pics:
    # 按顺序构造出图片路径
    img = os.path.join("./he/",im)
    img1 = cv2.imread(img)
# 指定编码器
    print(img1)
 
# 写入视频
    out.write(img1)
    cv2.imshow("detections", img1)
# 注意:尺寸一定要和图像保持一致,否则看不了视频
# 如果想改变保存视频尺寸,应该先把读入的图像的尺寸改变
out.release()
cv2.destoryAllWindows()

加载全部内容

相关教程
猜你喜欢
用户评论