- 项目地址:https://aistudio.baidu.com/aistudio/projectdetail/2322820
电脑桌面单单调调,突然想起来(其实看到别人的桌面上的…)可以写一个动态人物挂件放在桌面上。
别人的桌面宠物~~~~
实现的思路:
- 对gif或者视频进行逐帧解析,获取转换的图片,提取图像中人体区域,并对图片进行批量尺寸大小修改替换;
- 初始化设置动画挂件窗体显示效果,窗体位置、大小等;
- 桌面动画挂件功能实现,动画轮播、鼠标控制挂件位置拖动;
- 挂件打包图标设置、打包配置;
实现的效果:
二、GIF/视频分帧 GIF分帧效果可以如此,也可以根据个人喜好随意更换人物模型!!!
from PIL import Image # 导入PIL的Image包
import os
gifFileName = "./work/demo.gif" # 把gif图赋值给gifFileName
im = Image.open(gifFileName) # 使用Image的open函数打开test.gif图像
pngDir = gifFileName[:-4] # 倒着从gifFileName中的倒数第四个开始取字符(跳过.gif),赋值给pngDir,作为文件夹的名字
if not os.path.exists(pngDir):
os.makedirs('./work/demo') # 用图片名创建一个文件夹,用来存放每帧图片,名字为pngDir的值
try:
while True: # 死循环
current = im.tell() # 用tell函数保存当前帧图片,赋值给current
im.save(pngDir+'/'+str(current+1)+'.png') # 调用save函数保存该帧图片
im.seek(current+1) # 调用seek函数获取下一帧图片,参数变为current帧图片+1
# 这里再次进入循环,当为最后一帧图片时,seek会抛出异常,代码执行except
except EOFError:
pass # 最后一帧时,seek抛出异常,进入这里,pass跳过
视频分帧
# 将视频按照每一帧转成图片png
import cv2
videoFileName = "./work/demo.mp4" # 把视频路径赋值给videoFileName
pngDir = videoFileName[:-4] # 倒着从gifFileName中的倒数第四个开始取字符(跳过.后缀),赋值给pngDir,作为文件夹的名字
if not os.path.exists(pngDir):
os.makedirs(pngDir) # 用图片名创建一个文件夹,用来存放每帧图片,名字为pngDir的值
# 视频处理 分割成一帧帧图片
cap = cv2.VideoCapture(videoFileName)
num = 1
while True:
# 逐帧读取视频 按顺序保存到本地文件夹
ret, frame = cap.read()
if ret:
cv2.imwrite(f"{pngDir}/{num}.png", frame) # 保存一帧帧的图片
num += 1
else:
break
cap.release() # 释放资源
%cd work/ #!mkdir results
/home/aistudio/work
三、人像分割上述两种方法根据自己需求来就可以!
import cv2
import numpy as np
from math import atan2, degrees
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from random import randrange
%matplotlib inline
# 待预测图片
test_img_path = ['./demo/1.png']
img = mpimg.imread(test_img_path[0])
# 展示待预测图片
plt.figure(figsize=(10,10))
plt.imshow(img)
plt.axis('off')
plt.show()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MO7eRZl2-1652864219624)(output_9_0.png)]
import cv2
import paddlehub as hub
human_seg = hub.Module(name="deeplabv3p_xception65_humanseg")
result = human_seg.segmentation(images=[cv2.imread('./demo/3.png')],visualization=True) # ,output_dir='./work/results'指定保存路径
#print(result)
Download https://bj.bcebos.com/paddlehub/paddlehub_dev/deeplabv3p_xception65_humanseg.tar.gz [##################################################] 100.00% Decompress /home/aistudio/.paddlehub/tmp/tmpu4p4rug7/deeplabv3p_xception65_humanseg.tar.gz [##################################################] 100.00% [2021-08-30 17:10:45,106] [ INFO] - Successfully installed deeplabv3p_xception65_humanseg-1.1.2 [2021-08-30 17:10:45,268] [ WARNING] - The _initialize method in HubModule will soon be deprecated, you can use the __init__() to handle the initialization of the object
import glob
from tqdm import tqdm
import time
import cv2
import paddlehub as hub
def seg(img_name):
#print(img_name)
human_seg = hub.Module(name="deeplabv3p_xception65_humanseg")
result = human_seg.segmentation(images=[cv2.imread('./demo/'+str(img_name))],visualization=True)
path_file_number=glob.glob('demo/*.png')#或者指定文件下个数
#path_file_number=glob.glob(pathname='*.py') #获取当前文件夹下个数
#print(path_file_number)
#print(len(path_file_number))
for i in tqdm(range(len(path_file_number))):
name = i+1
#time.sleep(1)
seg(str(name)+'.png')
0%| | 0/91 [00:00, ?it/s] Download https://bj.bcebos.com/paddlehub/paddlehub_dev/deeplabv3p_xception65_humanseg.tar.gz [##################################################] 100.00% Decompress /home/aistudio/.paddlehub/tmp/tmpx7fxzail/deeplabv3p_xception65_humanseg.tar.gz [##################################################] 100.00% [2021-08-30 17:33:21,999] [ INFO] - Successfully installed deeplabv3p_xception65_humanseg-1.1.2 [2021-08-30 17:33:22,136] [ WARNING] - The _initialize method in HubModule will soon be deprecated, you can use the __init__() to handle the initialization of the object 1%| | 1/91 [00:14<21:40, 14.45s/it][2021-08-30 17:33:26,640] [ WARNING] - The _initialize method in HubModule will soon be deprecated, you can use the __init__() to handle the initialization of the object 2%|▏ | 2/91 [00:18<16:50, 11.36s/it][2021-08-30 17:33:30,787] [ WARNING] - The _initialize method in HubModule will soon be deprecated, you can use the __init__() to handle the initialization of the object 3%|▎ | 3/91 [00:22<13:29, 9.20s/it][2021-08-30 17:33:34,941] [ WARNING] - The _initialize method in HubModule will soon be deprecated, you can use the __init__() to handle the initialization of the object ... 96%|█████████▌| 87/91 [06:16<00:17, 4.36s/it][2021-08-30 17:39:28,580] [ WARNING] - The _initialize method in HubModule will soon be deprecated, you can use the __init__() to handle the initialization of the object 97%|█████████▋| 88/91 [06:20<00:12, 4.31s/it][2021-08-30 17:39:32,763] [ WARNING] - The _initialize method in HubModule will soon be deprecated, you can use the __init__() to handle the initialization of the object 98%|█████████▊| 89/91 [06:24<00:08, 4.29s/it][2021-08-30 17:39:37,118] [ WARNING] - The _initialize method in HubModule will soon be deprecated, you can use the __init__() to handle the initialization of the object 99%|█████████▉| 90/91 [06:29<00:04, 4.29s/it][2021-08-30 17:39:41,301] [ WARNING] - The _initialize method in HubModule will soon be deprecated, you can use the __init__() to handle the initialization of the object 100%|██████████| 91/91 [06:33<00:00, 4.32s/it]
'''
# 忽略,该部分是测试代码
imgdir = './demo'
IMAGES_LIST = os.listdir(imgdir)
for image_name in IMAGES_LIST:
print(image_name)
#break
# 判断后缀只处理jpg文件
if image_name.endswith('.jpg'):
image = cv2.imread(os.path.join(imgdir, image_name))
#print(image)
coordinates_list = object_detec('./work/images/'+image_name)
'''
四、大小重置
import os
from PIL import Image
file_list = os.listdir("./humanseg_output") # 读取当前文件夹所有文件
# print(file_list)
n = len(file_list)
for i in tqdm(range(n)):
s = str(file_list[i])
if s[-4:] == ".png": # 检查后缀
src = os.path.join(os.path.abspath('./humanseg_output/'), s) # 原先的图片名字
img = Image.open(src)
new_img = img.resize((128, 128), Image.BILINEAR)
new_img.save(src)
100%|██████████| 91/91 [00:00<00:00, 97.83it/s]五、下载到本地并重命名
-
打包humanseg_output文件夹并下载到本地;
-
新建文件并命名为rename.bat(里面代码如下),把这个rename.bat放到下载的humanseg_output文件夹,并双击,重命名完成:
@echo off
setlocal enabledelayedexpansion
set count=100
for /f "delims=" %%i in ('dir /b *.jpg,*.png,*.bmp,*.jpeg,*.gif') do call:Rename "%%~i"
pause
exit
:Rename
set /a count+=1
if /i "%~1"=="!count:~1!%~x1" goto :eof
if exist "!count:~1!%~x1" goto Rename
echo rename:%1 !count:~1!
ren "%~1" "!count:~1!%~x1"
goto :eof
六、桌面挂件
import sys
import os
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class Qt_pet(QWidget):
def __init__(self):
super(Qt_pet, self).__init__()
self.dis_file = "yiyi"
self.windowinit()
self.icon_quit()
self.pos_first = self.pos()
self.img_count = len(os.listdir('./image/{}'.format(self.dis_file)))
self.timer = QTimer()
self.timer.timeout.connect(self.img_update)
self.timer.start(100)
def img_update(self):
if self.img_num < self.img_count:
self.img_num += 1
else:
self.img_num = 0
self.img_path = './image/{file}/{img}.png'.format(file=self.dis_file, img=str(self.img_num))
self.qpixmap = QPixmap(self.img_path)
self.lab.setPixmap(self.qpixmap)
def windowinit(self):
self.x = 1800
self.y = 800
self.setGeometry(self.x, self.y, 300, 300)
self.setWindowTitle('My Pet')
self.img_num = 1
self.img_path = './image/{file}/{img}.png'.format(file=self.dis_file, img=str(self.img_num))
self.lab = QLabel(self)
self.qpixmap = QPixmap(self.img_path)
self.lab.setPixmap(self.qpixmap)
self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.SubWindow)
self.setAutoFillBackground(False)
self.setAttribute(Qt.WA_TranslucentBackground, True)
self.show()
def icon_quit(self):
mini_icon = QSystemTrayIcon(self)
mini_icon.setIcon(QIcon('./image/img3/1.png'))
quit_menu = QAction('Exit', self, triggered=self.quit)
tpMenu = QMenu(self)
tpMenu.addAction(quit_menu)
mini_icon.setContextMenu(tpMenu)
mini_icon.show()
def mousePressEvent(self, QMouseEvent):
if QMouseEvent.button() == Qt.LeftButton:
self.pos_first = QMouseEvent.globalPos() - self.pos()
QMouseEvent.accept()
self.setCursor(QCursor(Qt.OpenHandCursor))
def mouseMoveEvent(self, QMouseEvent):
if Qt.LeftButton:
self.move(QMouseEvent.globalPos() - self.pos_first)
print(self.pos())
self.x, self.y = self.pos().x, self.pos().y
QMouseEvent.accept()
def quit(self):
self.close()
sys.exit()
if __name__ == '__main__':
app = QApplication(sys.argv)
pet = Qt_pet()
sys.exit(app.exec_())
| |--qt_yiyi.py |--image yiyi
文件存放位置
七、打包发布pip install Pyinstaller
pyinstaller -F -i ./img.ico qt_yiyi.py
如果没有ico的图片怎么办呢?
python除了生孩子,什么都会!!
import PythonMagick
# 生成图标ico(png格式图片转成ico)
img = PythonMagick.Image('./image/img1/1.png')
# 这里要设置一下尺寸,不然会报ico尺寸异常错误
img.sample('128x128')
img.write('./img.ico')
打包后的【依依】小姐姐桌宠就直接可以用了哦~
八、参考- PaddleHub人像分割模型



