用 Python 把你的朋友变成表情包(鼠标事件提取 ROI 版)
发布日期:2021-05-06 23:44:03 浏览次数:10 分类:技术文章

本文共 2321 字,大约阅读时间需要 7 分钟。

文章目录

说明

在一文中,我们已经实现了朋友 → \rightarrow 表情包的友好转换。因为有些朋友给我留言觉得在第八个步骤(将一些不需要的黑色区域删除掉)中选定区域那里过于繁琐了,所以在这篇文章的代码中,我们将这一步用调用鼠标事件的方式实现这一步。

第八步改进版

在改进前的代码中,我们通过手动选择三角形或矩形区域来删掉不需要的黑色部分,这样一来比较费眼力,二来选择区域不是很准确。因此,在改进版中,我们使用鼠标事件来直接将黑色区域删除。其具体代码如下:

def draw_circle(event,x,y,flags,param):    if event==cv2.EVENT_MOUSEMOVE:        cv2.circle(image_rotate,(x,y),3,(255,255,255),-1)cv2.namedWindow('image')cv2.setMouseCallback('image',draw_circle)  # 设置鼠标响应 while(1):    cv2.imshow('image', image_rotate)    if cv2.waitKey(20) & 0xFF==27:  # 按 Esc 退出        breakcv2.destroyAllWindows()plt_show(image_rotate)

运行代码后,我们会得到如下窗口:

在这里插入图片描述
当我们把鼠标在黑色区域滑动时,黑色区域就被涂白了,这样就方便了很多。

完整代码

import cv2import numpy as npimport matplotlib.pyplot as pltfrom PIL import Image, ImageDraw, ImageFontdef 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))# 填充不需要的区域def draw_circle(event,x,y,flags,param):    if event==cv2.EVENT_MOUSEMOVE:        cv2.circle(image_rotate,(x,y),3,(255,255,255),-1)cv2.namedWindow('image')cv2.setMouseCallback('image',draw_circle) while(1):    cv2.imshow('image', image_rotate)    if cv2.waitKey(20) & 0xFF==27:        breakcv2.destroyAllWindows()foreground = image_rotate[0: 93, 0: 125]foreground_resize = cv2.resize(foreground, None, fx=2.5, fy=2.5, interpolation = cv2.INTER_CUBIC)background = cv2.imread('back.jpg', 0)  # 导入背景图片# 拼接两张图片h_f, w_f = foreground_resize.shapeh_b, w_b = background.shapeleft = (w_b - w_f)//2right = left + w_ftop = 80bottom = top + h_femoji = backgroundemoji[top: bottom, left: right] = foreground_resizePilImg = Image.fromarray(emoji)  # cv2 转 PILdraw = 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 转回 cv2cv2.imwrite('./emoji.png', np.array(emoji_text))  # 保存表情包
上一篇:OpenCV+Python 让你的朋友出现在《法制进行时》
下一篇:基于 OpenCV 的车辆检测系统

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2025年04月02日 12时56分49秒