700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Python利用paddlehub实现批量抠图和更换证件照背景底色

Python利用paddlehub实现批量抠图和更换证件照背景底色

时间:2020-11-12 13:47:35

相关推荐

Python利用paddlehub实现批量抠图和更换证件照背景底色

Python利用paddlehub实现批量抠图和更换证件照背景底色,图片使用卓别林的个人肖像,代码来源抠图功能实现的博客。代码做了一些更改已实现蓝底背景功能,并实现边界框图提取。

import osfrom tkinter import Imageimport paddlehub as hubimport numpy as npimport cv2import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号# 获取需要抠图的图像文件地址# 图像文件目录地址path = r"D:\\demo_works\\Python\\0827\\picture1\\"# 遍历获取每张图像的地址files = [path + i for i in os.listdir(path)]# 显示所有原图像# 保存图像数据列表img = []# 创建画布 定义大小plt.figure(figsize=(8, 6))# 遍历获取每张图像数据for i, img_fine in enumerate(files):# 通过opencv获取图像数据并添加到列表img.append(cv2.imread(img_fine))# 由于opencv打开的图像格式为BGR 所以需要转换为RGB格式img[i] = cv2.cvtColor(img[i], cv2.COLOR_BGR2RGB)# 显示图像大小# print(img[i].shape)# 创建子视图#plt.subplot(2, len(files), i + 1)# 显示图像#plt.imshow(img[i])#plt.title("原图")# 调用飞浆的deeplabv3p_xception65_humanseg模型 该模型能够用于人像抠图#module = hub.Module(name="deeplabv3p_xception65_humanseg")module = hub.Module(name="deeplabv3p_xception65_humanseg")# 图像地址 (固定格式,不要更改)input_dict = {"image": files}# 训练模型并预测模型,打印结果(获取到抠图人像)results = module.segmentation(data=input_dict)i_image = 0# 列表存储抠图人像(方便保存数据,也可下载图像)newimgs = []for i in range(len(files)):# 提取抠图人像数据prediction = results[i]["data"]# 显示抠图后的轮廓图像#plt.imshow(prediction)# 根据图像成像还原数据(具体原理我也不知道)newimg = np.zeros(img[i].shape)shape_i = img[i].shapeprint(newimg.shape)#print(np.ndarray.size())print(prediction[:,:])print(prediction.shape)print(type(prediction))#breaknewimg[:, :, 0] = img[i][:, :, 0] * (prediction <= 0)*0newimg[:, :, 1] = img[i][:, :, 1] * (prediction <= 0)*0newimg[:, :, 2] = img[i][:, :, 2] / img[i][:, :, 2]*(prediction <= 0)*236newimg[:, :, 0] = newimg[:, :, 0]+img[i][:, :, 0] * (prediction > 0)newimg[:, :, 1] = newimg[:, :, 1]+img[i][:, :, 1] * (prediction > 0)newimg[:, :, 2] = newimg[:, :, 2]+img[i][:, :, 2] * (prediction > 0) #+ 236 * (prediction > 0)#newimg2 = np.zeros(prediction.shape)newimg2 = predictionfor ii in range(shape_i[1]):for jj in range(shape_i[2]):#flag = 0#for kk in range(3):if(prediction[ii,jj]!=0.0):newimg2[ii,jj] = 125.0else:newimg2[ii,jj] = 220.0#if(flag == 1):#print("\n here ha \n")# newimg2[ii,jj, 0] = 0# newimg2[ii,jj, 1] = 0# newimg2[ii,jj, 2] = 236 i_image = i_image + 1print(i_image)plt.figure(i_image)plt.xlabel("图像1") plt.imsave(path+str(i_image+8)+".jpg",newimg.astype(np.uint8))plt.imshow(newimg.astype(np.uint8)) i_image = i_image + 1print(i_image)plt.figure(i_image)plt.xlabel("图像2") plt.imshow(newimg2) # 添加到列表 newimg.astype(np.uint8)修改数据类型为uint8newimgs.append(newimg.astype(np.uint8))# 显示图像#plt.subplot(2, len(files), i + 1 + len(files))#plt.imshow(newimgs[i])#plt.xlabel("抠图后图像")# 总图像显示(少了这个就没图像了,千万别少了)plt.show()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。