猫史档案馆


【Python作品分享】用Python把朋友变成表情包【作品秀】

用户:坦率的木叶龙7bzN坦率的木叶龙7bzN查看:0 回复:2 评论:0 创建时间:2021-03-20T14:02:03


【作品展示】

center_image

 

【作品介绍】

可以把你的朋友也做成表情包哦

 

【作品源代码】

import cv2
import numpy as mp
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw, ImageFont


def plt_show(img):
    imageRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    plt.imshow(imageRGB)
    plt.show()


image = cv2.imread('SXC.jpg', 0)  # 导入前景图片

image_resize = cv2.resize(image, None, fx=0.3, fy=0.3,
                          interpolation=cv2.INTER_CUBIC)  # 缩放

ret, image_binary = cv2.threshold(
    image_resize, 80, 255, cv2.THRESH_BINARY)  # 图片二值化

image_roi = image_binary[74: 185, 0: 150]  # 感兴趣区域

rows, cols = image_roi.shape
# 旋转
M = cv2.getRotationMatrix2D(((cols-1)/2.0, (rows-1)/2.0), 15, 1)
image_rotate = cv2.warpAffine(image_roi, M, (140, 130))
# 填充不需要的区域
h, w = image_rotate.shape
image_rotate_copy = image_rotate.copy()
pts1 = np.array([[0, 20],  [喵, 0], [0, 0]], np.int32)
pts2 = np.array([[0, 18],  [0, h], [80, h]], np.int32)
pts3 = np.array([[0, 100],  [0, h], [w, h], [w, 100]], np.int32)
pts4 = np.array([[111, 0],  [w, 0], [w, 30]], np.int32)
pts5 = np.array([[124, 0],  [115, h], [w, h]], np.int32)
pts6 = np.array([[120, 40],  [95, 100], [120, 100]], np.int32)
foreground = cv2.fillPoly(image_rotate_copy, [pts1], (255, 255, 255))
foreground = cv2.fillPoly(image_rotate_copy, [pts2], (255, 255, 255))
foreground = cv2.fillPoly(image_rotate_copy, [pts3], (255, 255, 255))
foreground = cv2.fillPoly(image_rotate_copy, [pts4], (255, 255, 255))
foreground = cv2.fillPoly(image_rotate_copy, [pts5], (255, 255, 255))
foreground = cv2.fillPoly(image_rotate_copy, [pts6], (255, 255, 255))

foreground_roi = foreground[0: 93, 0: 125]
foreground_roi_resize = cv2.resize(
    foreground_roi, None, fx=2.5, fy=2.5, interpolation=cv2.INTER_CUBIC)

background = cv2.imread('back.jpg', 0)  # 导入背景图片
# 拼接两张图片
h_f, w_f = foreground_roi_resize.shape
h_b, w_b = background.shape
left = (w_b - w_f)//2
right = left + w_f
top = 80
bottom = top + h_f
emoji = background
emoji[top: bottom, left: right] = foreground_roi_resize

PilImg = Image.fromarray(emoji)  # cv2 转 PIL
draw = ImageDraw.Draw(PilImg)  # 创建画笔
ttfront = ImageFont.truetype('simhei.ttf', 34)  # 设置字体
draw.text((210, 450), "你瞅啥!!", fill=0, font=ttfront)  # (位置,文本,文本颜色,字体)
emoji_text = cv2.cvtColor(np.array(PilImg), cv2.COLOR_RGB2BGR)  # PIL 转回 cv2

cv2.imwrite('./emoji.png', np.array(emoji_text))  # 保存表情包

 

【提示】

部分含有Python第三方库相关内容的作品,在海龟编辑器网页端无法运行哦!如遇到这种情况,可以打开下面的链接,下载海龟编辑器客户端:

https://python.codemao.cn


回复

上一页1 页 / 共 1下一页
阿啦斯佳阿啦斯佳

emotion_goodemotion_goodemotion_goodemotion_goodemotion_goodemotion_goodemotion_goodemotion_good

点赞0


评论


浮躁的飓风雀HYKa浮躁的飓风雀HYKa

cv2找不到

 

点赞0


评论