You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenCV C++视频转ASCII动画:仅捕获视频左上角区域问题求助

问题:视频转ASCII动画仅捕获画面左上角区域

我开发了一个将视频转为缩放后ASCII动画的C++程序,但cv::Mat frame仅能捕获视频的左上角部分区域。当前Mat的depth为0、channels为1,而且即便Mat显示为空,程序也必须使用at<uchar>才能正常运行。

我尝试过以下方法,但都没有解决问题:

  • 创建单独的Mat resizedFrame进行缩放
  • 为ASCII字符设置独立的宽高参数
  • 将resize()从预加载流程外移到帧读取循环内

附上程序代码如下:

#include <iostream>
#include <vector>
#include <chrono>
#include <thread>
#include <Windows.h>
#include <mmsystem.h>
#include <opencv2/opencv.hpp>

#pragma comment(lib, "winmm.lib")

void checkForOpenCV()
{
    if(cv::getCPUTickCount == 0)
    {
        std::cout << "OpenCV is not detected." << '\n';
    }
    else
    {
        std::cout << "OpenCV is detected." << '\n';
    }
}

cv::VideoCapture openVid(std::string &filePath)
{
    cv::VideoCapture cap{filePath};
    if(!cap.isOpened())
    {
        std::cout << "The file cannot be accessed." << '\n';
        exit(-1);
    }
    else
    {
        std::cout << "File is accessed." << '\n';
    }

    return cap;
}

char brightness2Ascii(int brightness, std::string asciiCharset)
{
    int index(brightness * asciiCharset.size() / 256);
    return asciiCharset[index];
}

int main()
{
    checkForOpenCV();

    std::string filePath{R"(C:\Users\Harold.DESKTOP-UJ6F4M4\Videos\video.mp4)"};
    cv::VideoCapture cap{openVid(filePath)};

    double fps{cap.get(cv::CAP_PROP_FPS)};
    std::cout << fps << '\n';

    int width(cap.get(cv::CAP_PROP_FRAME_WIDTH));
    int height(cap.get(cv::CAP_PROP_FRAME_HEIGHT));
    int aspectRatio{12};
    std::cout << width << " x " << height << '\n';

    std::vector<cv::Mat> totalFrames{};
    cv::Mat frame{};

    int depth{frame.depth()};
    int channels{frame.channels()};

    while(cap.read(frame))
    {
        cv::resize(frame, frame, cv::Size(width / aspectRatio, height / aspectRatio), 0, 0, cv::INTER_LINEAR);
        totalFrames.push_back(frame.clone());
    }
    cap.release();

    
    for(const auto &frame:totalFrames)
    {
        std::string asciiArt{};
        for(int i{0}; i < frame.rows; i++)
        {
            for(int j{0}; j < frame.cols; j++)
            {
                const std::string asciiCharset{" .'-=*%#@"}; // {" .'-=*%#@"} {"@ "}
                int brightness{frame.at<uchar>(i, j)};
                char pixelChar{brightness2Ascii(brightness, asciiCharset)};
                asciiArt += pixelChar;
            }
            asciiArt += '\n';
        }
std::cout << depth << '\n' << channels << '\n';
        std::cout << asciiArt;
        cv::waitKey(fps / 2);

    }

    return 0;
}

内容的提问来源于stack exchange,提问作者Alterna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 09:35:01