使用C++和opencv实现字符画视频

这个程序的核心思想是将视频的每帧作为图片处理,对每个像素的像素值,映射到某一个字符,再将所有的字符形成字符串,将每一帧对应的字符串打印出来,就可以在控制台看到动画

#include 
#include 
#include 
#include
#include
#include 
#pragma comment(lib,"WinMM.Lib")

using namespace cv;
using namespace std;

string char_list = ".,-'`:!1+*abcdefghijklmnopqrstuvwxyz<>():{}[]234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ%&@#$";//用来映射的字符串
float len = 255 /char_list.length();
int main()
{
	system("mode con cols=400 lines=200");//设定窗口大小
	VideoCapture cap;
	
	cap.open("E:\\1.mp4");//读入文件
	float fps = cap.get(CV_CAP_PROP_FPS);//求fps
	if (!cap.isOpened()) {
		cout << "can't open file" << endl;
		return -1;
	}
	Mat frame, frame_resize, frame_gray;
	clock_t start, finish;
	PlaySound(TEXT("D:\\FFOutput\\1.wav"), NULL, SND_ASYNC);//播放音频,可选
	while (true)
	{
		//system("cls");
		start = clock();

		cap >> frame;
		
		if (frame.empty())	break;
		resize(frame, frame_resize, Size(300, 90));//重新设定大小
		cvtColor(frame_resize, frame_gray, CV_BGR2GRAY);//转灰度图
		string txt = "";

		int height = frame_gray.rows;
		int width = frame_gray.cols;
		//cout << height << "  " << width << endl;
		//对每个像素操作
		for (int j = 0; j < height; j++) {
			for (int i = 0; i < width; i++)
			{
				float pdata = frame_gray.ptr<uchar>(j)[i];
				if ((int)pdata == 255)
				{
					char temp = ' ';
					txt +=temp;
				}
				else
				{
					char temp = char_list[int(pdata / len) ];
					if (temp == '\0')temp='0';
					txt += temp;
				}
			}
			txt += "\n";
		}
		
		//将光标移动到(0,0)处
		HANDLE hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
		COORD pos;
		pos.X = 0;
		pos.Y = 0;
		SetConsoleCursorPosition(hConsoleOutput, pos);

		//输出当前字符
		printf("%s", txt.c_str());
		finish = clock();
		float SLEEPTIME = 1000/fps - 1000*(finish - start) / CLOCKS_PER_SEC;
		Sleep(SLEEPTIME);//输出后休眠一段时间以符合原视频的速度
	}
	return 0;
}

你可能感兴趣的:(opencv)