文章目录
- np.hstack / np.vstack
- Slice
- cv2.addWeighted
- 自定义渐变式叠加
- cv2.bitwise_not / cv2.bitwise_and / cv2.add
np.hstack / np.vstack
利用 numpy 的 hstack 和 vstack,对图片进行拼接
import cv2
import numpy as nph, w = 256,256
img1 = cv2.resize(cv2.imread("1.jpg"), (w, h))
img2 = cv2.resize(cv2.imread("2.png"), (w, h))horizontal = np.hstack((img1, img2))
cv2.imwrite("horizontal.jpg", horizontal)vertical = np.vstack((img1, img2))
cv2.imwrite("vertical.jpg", vertical)
输入图片
horizontal
vertical
Slice
学习来自 Python 图像合并:利用 OpenCV 的强大功能
图片 reszie 成同样大小,生成空白图,利用切片,给相应区域赋值
import cv2
import numpy as npdimension = 256
canvas_dimension = 2 * dimensionimg1 = cv2.resize(cv2.imread("1.png"), (dimension, dimension))
img2 = cv2.resize(cv2.imread("2.png"), (dimension, dimension))
img3 = cv2.resize(cv2.imread("3.png"), (dimension, dimension))
img4 = cv2.resize(cv2.imread("4.png"), (dimension, dimension))canvas = np.zeros((canvas_dimension, canvas_dimension, 3), dtype=np.uint8)canvas[0:dimension, 0:dimension] = img1
canvas[0:dimension, dimension:canvas_dimension] = img2
canvas[dimension:canvas_dimension, 0:dimension] = img3
canvas[dimension:canvas_dimension, dimension:canvas_dimension] = img4# cv2.imwrite("merge.jpg", canvas)
cv2.imshow("merge", canvas)
cv2.waitKey(0)
cv2.destroyAllWindows()
输入图片1
输入图片2
输入图片3
输入图片4
合并结果
cv2.addWeighted
import cv2
w, h = 960, 540
img1 = cv2.resize(cv2.imread("1.jpg"), (w, h))
img2 = cv2.resize(cv2.imread("2.jpg"), (w, h))
merge = cv2.addWeighted(img1, 0.7, img2, 0.3, gamma=.0)
cv2.imwrite("merge.jpg", merge)
输入1
输入2
输出
自定义渐变式叠加
Python国庆头像制作
渐变透明度叠加
原图
from PIL import Imageflag = Image.open('1.png').convert("RGBA")
avatar = Image.open('2.jpg').convert("RGBA")flag = flag.resize(avatar.size)for i in range(flag.size[0]):for j in range(flag.size[1]):r, g, b, _ = flag.getpixel((i, j))alpha = max(0, 255 - i // 5 - j // 7) # 核心代码,左上角到右下角越来越透明# 重新填充像素flag.putpixel((i, j), (r, g, b, alpha))avatar.paste(flag, (0, 0), flag)
avatar.save('flag_avatar.png')
叠加后的效果
cv2.bitwise_not / cv2.bitwise_and / cv2.add
可以参考 【python】OpenCV—Paste Mask
A 图
A 图的 mask 标签
B 图
合并的结果