OpenCV 的一些基本用法,包括图像的读取、显示、修改和保存,以及视频处理的基础

下面为你提供一个使用 Python 生成视频的脚本。此脚本能够把一系列图像合成视频,也可以生成带有移动图形的动画视频。
此脚本有两个主要功能:

  1. images_to_video 函数:能够把指定文件夹里的图片合成为视频。
  2. generate_animation 函数:可以生成一个带有移动彩色圆形的简单动画视频。

使用前请先安装必要的依赖库:

pip install opencv-python numpy tqdm

若要使用图像生成视频,需要把示例中的路径修改为你自己图像所在的文件夹路径。要是你想生成动画视频,直接运行脚本即可。

import cv2
import numpy as np
from pathlib import Path
from tqdm import tqdm

def images_to_video(image_folder, output_path='output_video.mp4', fps=30.0):
    """
    将图像文件夹中的图片合成视频
    
    参数:
    image_folder (str): 包含图像的文件夹路径
    output_path (str): 输出视频的路径
    fps (float): 视频帧率
    """
    # 获取图片列表并排序
    image_files = sorted(Path(image_folder).glob('*.jpg'))
    if not image_files:
        image_files = sorted(Path(image_folder).glob('*.png'))
    
    if not image_files:
        print("错误: 未找到图像文件!")
        return
    
    # 读取第一张图片以获取尺寸
    frame = cv2.imread(str(image_files[0]))
    height, width, layers = frame.shape
    
    # 创建视频写入对象
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    video = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
    
    # 将每张图片写入视频
    for image_file in tqdm(image_files, desc="正在生成视频"):
        frame = cv2.imread(str(image_file))
        video.write(frame)
    
    # 释放资源
    video.release()
    print(f"视频已成功保存到: {output_path}")

def generate_animation(output_path='animated_video.mp4', fps=30.0, duration=10):
    """
    生成一个简单的动画视频
    
    参数:
    output_path (str): 输出视频的路径
    fps (float): 视频帧率
    duration (int): 视频时长(秒)
    """
    # 设置视频参数
    width, height = 800, 600
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    video = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
    
    # 计算总帧数
    total_frames = int(fps * duration)
    
    # 生成动画帧
    for frame_count in tqdm(range(total_frames), desc="正在生成动画"):
        # 创建黑色背景
        frame = np.zeros((height, width, 3), dtype=np.uint8)
        
        # 计算圆形位置(沿对角线移动)
        x = int(width * 0.5 + 200 * np.cos(frame_count * 0.05))
        y = int(height * 0.5 + 200 * np.sin(frame_count * 0.05))
        
        # 绘制彩色圆形
        color = (int(128 + 127 * np.sin(frame_count * 0.02)),
                 int(128 + 127 * np.sin(frame_count * 0.03)),
                 int(128 + 127 * np.sin(frame_count * 0.04)))
        cv2.circle(frame, (x, y), 50, color, -1)
        
        # 添加文本
        cv2.putText(frame, 'Python Video Generation', (50, 50),
                    cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
        
        # 写入帧
        video.write(frame)
    
    # 释放资源
    video.release()
    print(f"动画视频已成功保存到: {output_path}")

if __name__ == "__main__":
    # 示例1: 从图像生成视频
    # images_to_video('path/to/your/images', 'image_video.mp4', 25.0)
    
    # 示例2: 生成动画视频
    generate_animation('simple_animation.mp4', 30.0, 15)    

在 Python 中,OpenCV 是一个强大的计算机视觉库,可以用于图像处理、视频分析、对象检测等多种任务。下面我将介绍 OpenCV 的一些基本用法,包括图像读取、显示、修改和保存等操作。

1. 安装 OpenCV

首先需要安装 OpenCV 库:

pip install opencv-python

2. 基本图像处理操作

读取和显示图像
import cv2

# 读取图像(使用绝对路径或相对路径)
image = cv2.imread('path_to_your_image.jpg')

# 检查图像是否成功加载
if image is None:
    print("无法读取图像")
else:
    # 显示图像
    cv2.imshow('Original Image', image)
    
    # 等待按键事件(0表示无限等待)
    cv2.waitKey(0)
    
    # 关闭所有窗口
    cv2.destroyAllWindows()
转换为灰度图像
# 转换为灰度图像
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 显示灰度图像
cv2.imshow('Gray Image', gray_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
调整图像大小
# 调整图像大小(宽度和高度)
resized_image = cv2.resize(image, (500, 300))

# 或者按比例调整
resized_image = cv2.resize(image, None, fx=0.5, fy=0.5)

cv2.imshow('Resized Image', resized_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
保存图像
# 保存灰度图像
cv2.imwrite('gray_image.jpg', gray_image)

3. 图像滤波和增强

高斯模糊
# 高斯模糊(用于降噪)
blurred_image = cv2.GaussianBlur(image, (5, 5), 0)

cv2.imshow('Blurred Image', blurred_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
边缘检测
# Canny 边缘检测
edges = cv2.Canny(image, 100, 200)

cv2.imshow('Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()

4. 绘制形状和文本

绘制矩形
# 复制原图
image_with_rectangle = image.copy()

# 绘制矩形 (x,y) 左上角坐标,(w,h) 宽度和高度
x, y, w, h = 100, 100, 200, 150
cv2.rectangle(image_with_rectangle, (x, y), (x+w, y+h), (0, 255, 0), 2)

cv2.imshow('Image with Rectangle', image_with_rectangle)
cv2.waitKey(0)
cv2.destroyAllWindows()
添加文本
# 复制原图
image_with_text = image.copy()

# 添加文本
cv2.putText(image_with_text, 'Hello, OpenCV!', (50, 50), 
            cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)

cv2.imshow('Image with Text', image_with_text)
cv2.waitKey(0)
cv2.destroyAllWindows()

5. 视频处理基础

# 打开摄像头或视频文件
cap = cv2.VideoCapture(0)  # 0表示默认摄像头,也可以指定视频文件路径

while True:
    # 读取一帧
    ret, frame = cap.read()
    
    if not ret:
        print("无法获取帧")
        break
    
    # 显示帧
    cv2.imshow('Video', frame)
    
    # 按 'q' 键退出循环
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放资源
cap.release()
cv2.destroyAllWindows()

总结

以上是 OpenCV 的一些基本用法,包括图像的读取、显示、修改和保存,以及视频处理的基础操作。OpenCV 还提供了更多高级功能,如特征检测、对象识别、机器学习等,可以根据具体需求进一步学习和探索。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bol5261

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值