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
相关产品推荐
相关产品推荐

