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

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

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

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

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

import cv2
import numpy as np
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)) # 图像旋转
# 删除不需要的区域
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:
break
cv2.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.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[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/

你可能感兴趣的文章
Objective-C实现k-means clustering均值聚类算法(附完整源码)
查看>>
Objective-C实现k-Means算法(附完整源码)
查看>>
Objective-C实现k-nearest算法(附完整源码)
查看>>
Objective-C实现KadaneAlgo计算给定数组的最大连续子数组和算法(附完整源码)
查看>>
Objective-C实现kadanes卡达内斯算法(附完整源码)
查看>>
Objective-C实现kahns algorithm卡恩算法(附完整源码)
查看>>
Objective-C实现karatsuba大数相乘算法(附完整源码)
查看>>
Objective-C实现karger算法(附完整源码)
查看>>
Objective-C实现KMP搜索算法(附完整源码)
查看>>
Objective-C实现Knapsack problem背包问题算法(附完整源码)
查看>>
Objective-C实现knapsack背包问题算法(附完整源码)
查看>>
Objective-C实现knapsack背包问题算法(附完整源码)
查看>>
Objective-C实现knight tour骑士之旅算法(附完整源码)
查看>>
Objective-C实现knight Tour骑士之旅算法(附完整源码)
查看>>
Objective-C实现KNN算法(附完整源码)
查看>>
Objective-C实现KNN算法(附完整源码)
查看>>
Objective-C实现KNN算法(附完整源码)
查看>>
Objective-C实现knuth morris pratt(KMP)算法(附完整源码)
查看>>
Objective-C实现knuth-morris-pratt(KMP)算法(附完整源码)
查看>>
Objective-C实现Koch snowflake科赫雪花曲线算法(附完整源码)
查看>>