本文共 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)) # 保存表情包
转载地址:http://bhdq.baihongyu.com/