博客
关于我
用 Python 把你的朋友变成表情包(鼠标事件提取 ROI 版)
阅读量:315 次
发布时间:2019-03-03

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

在一文中,我们已经实现了朋友表情包的友好转换。由于部分朋友反馈在第八步(删除不需要的黑色区域)操作较为繁琐,我们在代码中采用调用鼠标事件的方式来实现这一步骤。

在改进前的代码中,我们通过手动选择三角形或矩形区域来删除不需要的黑色部分,这种方法不仅操作繁琐,而且精度不足。因此,改进版代码中我们直接使用鼠标事件来删除黑色区域,实现更加便捷和准确。

以下是改进后的代码示例:

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))  # 图像旋转# 删除不需要的区域cv2.namedWindow('image')cv2.setMouseCallback('image', draw_circle)def draw_circle(event, x, y, flags, param):    if event == cv2.EVENT_MOUSEMOVE:        cv2.circle(image_rotate, (x, y), 3, (255, 255, 255), -1)while True:    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_f# 调整后续区域emoji = background[top:bottom, left:right] = foreground_resize# 生成表情包PilImg = Image.fromarray(emoji)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)cv2.imwrite('./emoji.png', np.array(emoji_text))

运行代码后,系统会打开一个窗口。当您在黑色区域上滑动鼠标时,黑色区域会被涂白,这大大提高了操作的便利性。

通过这种方式,我们成功将朋友表情包的友好转换实现得更加简便。

转载地址:http://bhdq.baihongyu.com/

你可能感兴趣的文章
Python-Asyncio TypeError:无法在‘;等待‘;表达式中使用对象DICT
查看>>
Python-AttributeError:‘;dict&39;对象没有属性‘;序列‘;
查看>>
Python-ldap:是否可以在不显式写入密码的情况下进行绑定?
查看>>
python出现 unknown encoding: idna 的处理方法
查看>>
Python出现 RuntimeError: dictionary changed size during iteration 的解决方法
查看>>
Python-numpy(2)数组的操作
查看>>
Python-Numpy的tile函数用法
查看>>
python-open函数
查看>>
Python-Pandas-将特定函数应用于给定级别-多索引数据框架
查看>>
python-queue队列通信
查看>>
python-ros No module named PyKDL
查看>>
python-social-auth 是否需要会话
查看>>
Python再获年度编程语言,微软或成最大赢家
查看>>
python-week5
查看>>
Python写表情包搜索工具(非常详细)零基础入门到精通,收藏这一篇就够了
查看>>
Python-【1】配置
查看>>
Python-从子文件夹执行绝对导入
查看>>
Python-刷新页面,直到元素可单击
查看>>
PYTHON-唤醒+VOSK+DEEPSEEK+离线合成-实现纯离线大模型问答
查看>>
Python-在Dash回调中重用函数
查看>>