博客
关于我
用 Python 把你的朋友变成表情包(鼠标事件提取 ROI 版)
阅读量:314 次
发布时间: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/

你可能感兴趣的文章