在这里插入图片描述

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.videoio.VideoCapture;
import org.opencv.videoio.VideoWriter;

public class VideoSubtitles {
    public static void main(String[] args) {
        // 加载OpenCV原生库
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

        String inputVideo = "input.mp4";
        String outputVideo = "output.mp4";
        String subtitleText = "视频标题"; // 要添加的字幕文字

        try {
            // 打开输入视频文件
            VideoCapture capture = new VideoCapture(inputVideo);
            if (!capture.isOpened()) {
                System.out.println("无法打开输入视频文件");
                return;
            }

            // 获取视频宽度和高度
            int width = (int) capture.get(VideoCapture.CAP_PROP_FRAME_WIDTH);
            int height = (int) capture.get(VideoCapture.CAP_PROP_FRAME_HEIGHT);

            // 设置输出视频参数
            VideoWriter writer = new VideoWriter();
            Size frameSize = new Size(width, height);
            writer.open(outputVideo, VideoWriter.FOURCC_XVID, 25.0, frameSize, true);

            Mat frame = new Mat();

            while (capture.read(frame)) {
                // 在帧上添加字幕
                int fontFace = Core.FONT_HERSHEY_SIMPLEX;
                double fontScale = 1.0;
                int thickness = 2;

                // 设置文字位置和样式
                int orgX = 10; // x坐标(从左开始)
                int orgY = 50; // y坐标(从上开始)
                int[] color = {255, 255, 255}; // 白色字体
                int[] backColor = {0, 0, 0};    // 黑色背景

                // 先绘制背景矩形
                Core.rectangle(frame, new org.opencv.core.Point(orgX - 10, orgY - 10), 
                             new org.opencv.core.Point(orgX + subtitleText.length() * 20 + 10, orgY + 30),
                             backColor, -1);

                // 添加文字
                Core.putText(frame, subtitleText, new org.opencv.core.Point(orgX, orgY), fontFace,
                            fontScale, color, thickness);

                // 写入输出视频
                writer.write(frame);
            }

            capture.release();
            writer.release();

        } catch (Exception e) {
            System.out.println("异常:" + e.getMessage());
        }
    }
}

更多精彩,戳下方名片

Logo

欢迎加入DeepSeek 技术社区。在这里,你可以找到志同道合的朋友,共同探索AI技术的奥秘。

更多推荐