国庆节了,用OpenCV实现渐变版国庆头像,用技术给给自己换个国庆版头像!
生成的效果,头像比例有点不好,导致有点压缩。
实现这个其实超级简单,只需要两步!
第一步,找一张国旗模板图象,然后生成mask模板;
第二步,选择一张头像图象,根据mask权重与模板图象重新像素叠加混合。就生成了国庆版渐变头像了;
Python代码(需要安装opencv-python):
- import cv2 as cv
- import numpy as np
- def auto_mask_demo(image):
- gq = cv.imread("C:/Users/Criss/Desktop/gq.png")
- cv.imshow("input", gq)
- # 生成mask区域
- h, w, c = gq.shape
- mask = np.zeros((h, w), dtype=np.float32)
- for row in range(h):
- start = int(np.abs(np.sin(row * np.pi / 180) * 50))
- mask[row, start:w] = np.linspace(0, 255, w-start)
- mask = mask / 255.0
- cv.imshow("mask", mask)
- # generate icon
- dst = cv.resize(image, (w, h), interpolation=cv.INTER_CUBIC)
- result = np.zeros_like(dst)
- for row in range(h):
- for col in range(w):
- w2 = mask[row, col]
- w1 = 1.0 - w2
- b1, g1, r1 = gq[row, col]
- b2, g2, r2 = dst[row, col]
- b = b1 * w1 + b2 * w2
- g = g1 * w1 + g2 * w2
- r = r1 * w1 + r2 * w2
- result[row, col] = (int(b), int(g), int(r))
- cv.imshow("profile image", result)
- cv.imwrite("D:/result.png", result)
- cv.waitKey(0)
- cv.destroyAllWindows()
- if __name__ == "__main__":
- src = cv.imread("C:/Users/Criss/Desktop/headimage.png")
- auto_mask_demo(src)
复制代码
代码中图像下载:
Img.zip
(2 MB, 下载次数: 9)
原文来自【OpenCV学堂】,代码测试后稍作了修改。
|