将多张图片生成一个渐变的效果图
这段代码使用了OpenCV库来将两组图片逐步融合生成一个视频,视频中逐帧展示两张图片之间的过渡效果,并在过渡过程中画出一条竖线。
import cv2
import os
import numpy as np
# 读取两张图片
img1 = cv2.imread('data/2img2video/IM-1210-0015.jpg')
img2 = cv2.imread('data/2img2video/IM-1210-0015_SwinIR.png')
img3 = cv2.imread('runs/segment/predict5/IM-1210-0015_SwinIR.png')
height1, width1, layers1 = img1.shape
height2, width2, layers2 = img2.shape
if height1 * width1 > height2 * width2 :img2 = cv2.resize(img2, (height1, width1))
else:img1 = cv2.resize(img1, (height2, width2))output_video_name = 'output_video.mp4'
# 使用VideoWriter创建视频对象
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # 使用MP4编解码器
out = cv2.VideoWriter(output_video_name, fourcc, 30, (img1.shape[1], img1.shape[0]))# 创建新的图片
# 创建全黑图像for i in range(1, img1.shape[1], 10):black_image = np.zeros((img1.shape[0], img1.shape[1], 3), dtype=np.uint8)black_image[:, i:, :] = img1[:, i:, :]black_image[:, :i, :] = img2[:, :i, :]# 指定竖线的位置和颜色line_color = (176, 167, 248) # 绿色,格式为 (B, G, R)line_thickness = 2line_position_x = i # 你想要画线的位置的 x 坐标# 在图像上画竖线cv2.line(black_image, (line_position_x, 0), (line_position_x, black_image.shape[0]), line_color, line_thickness)out.write(black_image)for i in range(1, img2.shape[1], 10):black_image = np.zeros((img2.shape[0], img2.shape[1], 3), dtype=np.uint8)black_image[:, i:, :] = img2[:, i:, :]black_image[:, :i, :] = img3[:, :i, :]# 指定竖线的位置和颜色line_color = (176, 167, 248) # 绿色,格式为 (B, G, R)line_thickness = 2line_position_x = i # 你想要画线的位置的 x 坐标# 在图像上画竖线cv2.line(black_image, (line_position_x, 0), (line_position_x, black_image.shape[0]), line_color, line_thickness)out.write(black_image)# 释放资源
out.release()
cv2.destroyAllWindows()print("视频已生成:", output_video_name)