1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| # coding:utf8 import cv2
# 加个圣诞帽 def image_christmas_hat(img, x, y, w, h): hat = cv2.imread('ChristmasHat.jpg') # 帽子透明图片 hat = cv2.resize(hat, (0, 0), fx=0.2, fy=0.2, interpolation=cv2.INTER_NEAREST) # 稍微调整下大小 y = y-(h*3//4) _hat = cv2.resize(hat, (w, h)) rows, cols, channels = _hat.shape r, c, cs = img.shape if y+rows > r or x+cols > c: return img roi = img[y:(y+rows), x:(x+cols)] # 在原始图像中截取帽子图像大小的部分 img2gray = cv2.cvtColor(_hat, cv2.COLOR_BGR2GRAY) # 将logo图像灰度化 ret, mask = cv2.threshold(img2gray, 250, 255, cv2.THRESH_BINARY) # 将帽子灰度图二值化,将得到的图像赋值给mask,帽子部分的值为255,白色 mask_inv = cv2.bitwise_not(mask) # 将mask按位取反,即白变黑,黑变白 img1_bg = cv2.bitwise_and(roi, roi, mask=mask) # 将原始图像中截取的部分做处理,mask中黑色部分按位与运算,即保留黑色部分,保留除帽子位置外的部分 img2_fg = cv2.bitwise_and(_hat, _hat, mask=mask_inv) # 将帽子图像中,mask_inv部分按位与运算,即保留黑色部分,保留logo dst = cv2.add(img1_bg, img2_fg) # 图像相加 img[y:(y+rows), x:(x+cols)] = dst # 图像替换 return img
# 替换人脸为笑哭表情 def image_face(img, x, y, w, h): face = cv2.imread('xiaoku.jpg') # 笑哭脸透明图片 face = cv2.resize(face, (0, 0), fx=0.2, fy=0.2, interpolation=cv2.INTER_NEAREST) # 稍微调整下大小 _face = cv2.resize(face, (w, h)) rows, cols, channels = _face.shape r, c, cs = img.shape if y+rows > r or x+cols > c: return img roi = img[y:(y+rows), x:(x+cols)] # 在原始图像中截取表情图像大小的部分 img2gray = cv2.cvtColor(_face, cv2.COLOR_BGR2GRAY) # 将logo图像灰度化 ret, mask = cv2.threshold(img2gray, 250, 255, cv2.THRESH_BINARY) # 将表情灰度图二值化,将得到的图像赋值给mask,表情部分的值为255,白色 mask_inv = cv2.bitwise_not(mask) # 将mask按位取反,即白变黑,黑变白 img1_bg = cv2.bitwise_and(roi, roi, mask=mask) # 将原始图像中截取的部分做处理,mask中黑色部分按位与运算,即保留黑色部分,保留除表情位置外的部分 img2_fg = cv2.bitwise_and(_face, _face, mask=mask_inv) # 将表情图像中,mask_inv部分按位与运算,即保留黑色部分,保留logo dst = cv2.add(img1_bg, img2_fg) # 图像相加 img[y:(y+rows), x:(x+cols)] = dst # 图像替换 return img
# 替换为熊本熊 def image_Kumamon(img, x, y, w, h): Kumamon = cv2.imread('Kumamon.jpg') # 熊本熊透明图片 Kumamon = cv2.resize(Kumamon, (0, 0), fx=0.2, fy=0.2, interpolation=cv2.INTER_NEAREST) # 稍微调整下大小 x = x - w//2 w = w * 2 h = h * 2 _Kumamon = cv2.resize(Kumamon, (w, h)) rows, cols, channels = _Kumamon.shape r, c, cs = img.shape if y+rows > r or x+cols > c: return img roi = img[y:(y+rows), x:(x+cols)] # 在原始图像中截取熊本熊图像大小的部分 img2gray = cv2.cvtColor(_Kumamon, cv2.COLOR_BGR2GRAY) # 将logo图像灰度化 ret, mask = cv2.threshold(img2gray, 252, 255, cv2.THRESH_BINARY) # 将熊本熊灰度图二值化,将得到的图像赋值给mask,熊本熊部分的值为255,白色 mask_inv = cv2.bitwise_not(mask) # 将mask按位取反,即白变黑,黑变白 img1_bg = cv2.bitwise_and(roi, roi, mask=mask) # 将原始图像中截取的部分做处理,mask中黑色部分按位与运算,即保留黑色部分,保留除熊本熊位置外的部分 img2_fg = cv2.bitwise_and(_Kumamon, _Kumamon, mask=mask_inv) # 将熊本熊图像中,mask_inv部分按位与运算,即保留黑色部分,保留logo dst = cv2.add(img1_bg, img2_fg) # 图像相加 img[y:(y+rows), x:(x+cols)] = dst # 图像替换 return img
|