curosr使用c++实现图片视频转字符画风格带gui

news/2025/3/15 3:31:33/

talk is cheap show you the code

99%的代码都是通过cursor写出来的,提示太长了会卡住,所以最好先列一个提纲,每个步骤一定要详细
比如

  • 实现一个函数,输入图片路径,然后把图片转换成字符画,再把字符画保存为图片
  • 实现一个函数把视频转换为字符画,调用上面的转换图片函数
  • 使用win32实现一个gui,上面是按钮内容是选择图片,下面是一个图片展示框,点击图片弹出选择文件,选择完文件调用上面的转换图片为字符画函数,然后把图片显示在下面的显示框中
  • 在选择图片按钮下添加一个选择视频,在右边再添加一个进度条,弹出文件选择框选择视频调用视频转字符画函数处理视频并更新进度条
  • 写一个cmake文件,编译这个项目

gui效果图

gui

source code

#include <Windows.h>
#include <CommCtrl.h>
#include <string>
#include <iostream>
#include <fstream>
#include <thread>#pragma comment(lib, "Comctl32.lib")// 包含OpenCV头文件
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>// Implement the pixelValueToAsciiChar function
char pixelValueToAsciiChar(int pixelValue) {const std::string asciiChars = "MNHQ$OC?7>!:-;. ";return asciiChars[pixelValue / (256 / asciiChars.length())];
}// Convert image to ASCII art and save the ASCII art as an image
cv::Mat imageToCharPixel(const cv::Mat& inputImage) {// Resize the input imagecv::Mat resizedImage;cv::resize(inputImage, resizedImage, cv::Size(inputImage.cols / 2, inputImage.rows / 4));// Create an empty image for the ASCII artcv::Mat asciiImage(resizedImage.rows * 16, resizedImage.cols * 8, CV_8UC1, cv::Scalar(255));// Convert the resized image to ASCII artfor (int i = 0; i < resizedImage.rows; ++i) {for (int j = 0; j < resizedImage.cols; ++j) {// Get the pixel valueint pixelValue = resizedImage.at<uchar>(i, j);// Convert the pixel value to an ASCII characterchar asciiChar = pixelValueToAsciiChar(pixelValue);// Draw the ASCII character on the ASCII imagecv::putText(asciiImage, std::string(1, asciiChar), cv::Point(j * 8, i * 16),cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0), 1);}}// Return the ASCII art as an imagereturn asciiImage;
}cv::Mat imageToCharPixel2(const cv::Mat& inputImage) {// Resize the input imagecv::Mat resizedImage;cv::resize(inputImage, resizedImage, cv::Size(inputImage.cols/2, inputImage.rows/4));// Create an empty image for the ASCII artcv::Mat asciiImage(resizedImage.rows*16 , resizedImage.cols*8, CV_8UC1, cv::Scalar(255));// Convert the resized image to ASCII artfor (int i = 0; i < resizedImage.rows; ++i) {for (int j = 0; j < resizedImage.cols; ++j) {// Get the pixel valueint pixelValue = resizedImage.at<uchar>(i, j);// Convert the pixel value to an ASCII characterchar asciiChar = pixelValueToAsciiChar(pixelValue);// Draw the ASCII character on the ASCII imagecv::putText(asciiImage, std::string(1, asciiChar), cv::Point(j * 8, i * 16),cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0), 1);}}// Return the ASCII art as an imagereturn asciiImage;
}// Convert image to ASCII art and save the ASCII art as an image
cv::Mat imageToCharPixel(const std::string& imagePath) {// Load the input imagecv::Mat inputImage = cv::imread(imagePath, cv::IMREAD_GRAYSCALE);// Convert the image to ASCII artcv::Mat asciiImage = imageToCharPixel(inputImage);// Save the ASCII art as an imagereturn asciiImage;
}HWND hLeftImage;
HWND hWnd;
HWND hProgressBar;// Convert video to ASCII art and save the ASCII art as a video
void videoToCharPixel(const std::string& videoPath, const std::string& outputPath) {// Open the input videocv::VideoCapture inputVideo(videoPath);// Get the input video's frame ratedouble fps = inputVideo.get(cv::CAP_PROP_FPS);// Get the input video's frame sizecv::Size frameSize = cv::Size(inputVideo.get(cv::CAP_PROP_FRAME_WIDTH)*4, inputVideo.get(cv::CAP_PROP_FRAME_HEIGHT)*4);
std::cout << "Frame size: " << frameSize.width << "x" << frameSize.height << std::endl;// Create the output video writercv::VideoWriter outputVideo(outputPath, cv::VideoWriter::fourcc('M', 'J', 'P', 'G'), fps, frameSize, false);// Process each frame of the input videocv::Mat frame;int count = 1;while (inputVideo.read(frame)) {// Convert the frame to ASCII artcv::cvtColor(frame, frame, cv::COLOR_BGR2GRAY);cv::Mat asciiFrame = imageToCharPixel2(frame);//cv::imwrite("resf"+std::to_string(count)+".jpg", frame);//cv::imwrite("res"+std::to_string(count)+".jpg", asciiFrame);// Write the ASCII frame to the output videooutputVideo.write(asciiFrame);
int progress = static_cast<int>((count / inputVideo.get(cv::CAP_PROP_FRAME_COUNT)) * 100);
SendMessage(hProgressBar, PBM_SETPOS, progress, 0);count++;}MessageBox(hWnd, "Video converted to ASCII art and saved as res.avi", "Conversion Complete", MB_OK);
}LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {switch (message) {// 处理WM_CLOSE消息case WM_CLOSE: DestroyWindow(hWnd); // 销毁窗口PostQuitMessage(0); // 退出应用程序break;// 其他消息处理case IDCANCEL:PostQuitMessage(0);break;default:return DefWindowProc(hWnd, message, wParam, lParam);}return 0;
}int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {// Initialize common controlsINITCOMMONCONTROLSEX icex;icex.dwSize = sizeof(INITCOMMONCONTROLSEX);icex.dwICC = ICC_STANDARD_CLASSES;InitCommonControlsEx(&icex);WNDCLASS wc = {0};wc.lpfnWndProc = WndProc;wc.hInstance = hInstance;wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND);wc.lpszClassName = "ASCII Art Generator";RegisterClass(&wc);// Create the main windowhWnd = CreateWindowEx(0, "ASCII Art Generator", "ASCII Art Generator", WS_OVERLAPPEDWINDOW,CW_USEDEFAULT, CW_USEDEFAULT, 800, 800, nullptr, nullptr, hInstance, nullptr);// Create the left image display controlhLeftImage = CreateWindowEx(0, WC_STATIC, nullptr, WS_CHILD | WS_VISIBLE | SS_BITMAP,100, 100, 600, 600, hWnd, nullptr, hInstance, nullptr);// Create the "Select Image" buttonHWND hSelectImageButton = CreateWindowEx(0, WC_BUTTON, "Select Image", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,50, 50, 100, 30, hWnd, nullptr, hInstance, nullptr);// Create the progress bar controlhProgressBar = CreateWindowEx(0, PROGRESS_CLASS, nullptr, WS_CHILD | WS_VISIBLE,160, 100, 600, 30, hWnd, nullptr, hInstance, nullptr);SendMessage(hProgressBar, PBM_SETRANGE, 0, MAKELPARAM(0, 100));SendMessage(hProgressBar, PBM_SETSTEP, 1, 0);// Add an event handler for the "Select Image" buttonstatic OPENFILENAME ofn;static char szFile[260];ZeroMemory(&ofn, sizeof(ofn));ofn.lStructSize = sizeof(ofn);ofn.hwndOwner = hWnd;ofn.lpstrFile = szFile;ofn.lpstrFile[0] = '\0';ofn.nMaxFile = sizeof(szFile);ofn.lpstrFilter = "Image Files (*.bmp;*.jpg;*.png)\0*.bmp;*.jpg;*.png\0All Files (*.*)\0*.*\0";ofn.nFilterIndex = 1;ofn.lpstrFileTitle = nullptr;ofn.nMaxFileTitle = 0;ofn.lpstrInitialDir = nullptr;ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;static HWND hDlg = hWnd;static HANDLE hImage = nullptr;// Create the "Select Video" buttonHWND hSelectVideoButton = CreateWindowEx(0, WC_BUTTON, "Select Video", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,50, 100, 100, 30, hWnd, nullptr, hInstance, nullptr);// Add an event handler for the "Select Video" buttonstatic OPENFILENAME ofnVideo;static char szVideoFile[260];ZeroMemory(&ofnVideo, sizeof(ofnVideo));ofnVideo.lStructSize = sizeof(ofnVideo);ofnVideo.hwndOwner = hWnd;ofnVideo.lpstrFile = szVideoFile;ofnVideo.lpstrFile[0] = '\0';ofnVideo.nMaxFile = sizeof(szVideoFile);ofnVideo.lpstrFilter = "Video Files (*.mp4;*.avi)\0*.mp4;*.avi\0All Files (*.*)\0*.*\0";ofnVideo.nFilterIndex = 1;ofnVideo.lpstrFileTitle = nullptr;ofnVideo.nMaxFileTitle = 0;ofnVideo.lpstrInitialDir = nullptr;ofnVideo.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;static auto selectVideo = []() {if (GetOpenFileName(&ofnVideo) == TRUE) {// Convert the video to ASCII art// Execute videoToCharPixel in a separate threadstd::thread t(videoToCharPixel, ofnVideo.lpstrFile, "res.avi");t.detach();}};SendMessage(hSelectVideoButton, BM_SETIMAGE, IMAGE_ICON, reinterpret_cast<LPARAM>(LoadIcon(nullptr, IDI_SHIELD)));SetWindowText(hSelectVideoButton, "Select Video");SetWindowSubclass(hSelectVideoButton, [](HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData) -> LRESULT {switch (uMsg) {case WM_LBUTTONUP:selectVideo();break;}return DefSubclassProc(hWnd, uMsg, wParam, lParam);}, 0, 0);static auto selectImage = []() {if (GetOpenFileName(&ofn) == TRUE) {// Convert the image to ASCII artcv::Mat asciiImage = imageToCharPixel(ofn.lpstrFile);cv::imwrite("res.jpg", asciiImage);// Calculate the height based on the aspect ratio and resize the imageint height = static_cast<int>(asciiImage.rows * (600.0 / asciiImage.cols));cv::resize(asciiImage, asciiImage, cv::Size(600, height), 0, 0, cv::INTER_AREA);
// Convert the ASCII image to a 3-channel imagecv::cvtColor(asciiImage, asciiImage, cv::COLOR_GRAY2BGR);cv::flip(asciiImage, asciiImage, 0);// Display the ASCII art on the left image controlHDC hdc = GetDC(hLeftImage);SetBkColor(hdc, RGB(255, 255, 255));BITMAPINFO bmi = { 0 };bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);bmi.bmiHeader.biWidth = asciiImage.cols;bmi.bmiHeader.biHeight = asciiImage.rows;bmi.bmiHeader.biPlanes = 1;bmi.bmiHeader.biBitCount = 24;bmi.bmiHeader.biCompression = BI_RGB;bmi.bmiHeader.biSizeImage = 0;HBITMAP hBitmap2 = CreateDIBitmap(hdc, &bmi.bmiHeader, CBM_INIT, asciiImage.data, &bmi, DIB_RGB_COLORS);SendMessage(hLeftImage, STM_SETIMAGE, IMAGE_BITMAP, reinterpret_cast<LPARAM>(hBitmap2));DeleteObject(hBitmap2);// Resize the window to fit the imageRECT rect;GetClientRect(hLeftImage, &rect);int width = rect.right - rect.left;int newHeight = static_cast<int>(asciiImage.rows * (width / static_cast<double>(asciiImage.cols)));std::cout << "newHeight: " << newHeight << std::endl;SetWindowPos(hLeftImage, nullptr, 0, 0, width, newHeight, SWP_NOMOVE | SWP_NOZORDER);}};SendMessage(hSelectImageButton, BM_SETIMAGE, IMAGE_ICON, reinterpret_cast<LPARAM>(LoadIcon(nullptr, IDI_SHIELD)));SetWindowText(hSelectImageButton, "Select Image");SetWindowSubclass(hSelectImageButton, [](HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData) -> LRESULT {switch (uMsg) {case WM_LBUTTONUP:selectImage();break;}return DefSubclassProc(hWnd, uMsg, wParam, lParam);}, 0, 0);// Show the main windowShowWindow(hWnd, nCmdShow);// Enter the message loopMSG msg;while (GetMessage(&msg, nullptr, 0, 0)) {TranslateMessage(&msg);DispatchMessage(&msg);}return static_cast<int>(msg.wParam);
}

cmake文件

cmake_minimum_required(VERSION 3.0)
project(ascii2img)find_package(OpenCV REQUIRED PATHS "D:/tools/opencv/build")include_directories(${OpenCV_INCLUDE_DIRS})add_executable(ascii2img WIN32 ascii2img.cpp)target_link_libraries(ascii2img ${OpenCV_LIBS})

编译程序

cmake -G “Visual Studio 17 2022” …
cmake --build .

打包绿色程序

c++打包绿色程序

下载打包好的程序
https://gitee.com/youngboyvip/acii2img/blob/master/ascii2img.zip


http://www.ppmy.cn/news/33682.html

相关文章

MySQL相关面试题解析(一)

文章目录 1.有如下数据库表,其中两个事务按照如下顺序执行,回答下列问题?2.同样是上面的数据库表,如果修改事务如下,回答下列问题?3.同样是上面的数据库表,如果修改事务如下,回答下列问题?1.有如下数据库表,其中两个事务按照如下顺序执行,回答下列问题? create ta…

蓝桥杯刷题冲刺 | 倒计时21天

作者&#xff1a;指针不指南吗 专栏&#xff1a;蓝桥杯倒计时冲刺 &#x1f43e;马上就要蓝桥杯了&#xff0c;最后的这几天尤为重要&#xff0c;不可懈怠哦&#x1f43e; 文章目录1.迷宫1.迷宫 题目 链接&#xff1a; 迷宫 - 蓝桥云课 (lanqiao.cn) 本题为填空题&#xff0c;只…

Redis缓存雪崩、缓存击穿、缓存穿透

用户的数据一般都是存储于数据库&#xff0c;数据库的数据是落在磁盘上的&#xff0c;磁盘的读写速度可以说是计算机里最慢的硬件了。 当用户的请求&#xff0c;都访问数据库的话&#xff0c;请求数量一上来&#xff0c;数据库很容易就奔溃的了&#xff0c;所以为了避免用户直…

jsoup 框架的使用指南

概述 参考&#xff1a; 官方文档jsoup的使用JSoup教程jsoup 在 GitHub 的开源代码 概念简介 jsoup 是一款基于 Java 的 HTML 解析器&#xff0c;它提供了一套非常省力的 API&#xff0c;不但能直接解析某个 URL 地址、HTML 文本内容&#xff0c;而且还能通过类似于 DOM、CS…

浏览器的组成部分

什么是浏览器&#xff1f; Web 浏览器简称为浏览器&#xff0c;是一种用于访问互联网上信息的应用软件。浏览器的主要功能是从服务器检索 Web 资源并将其显示在 Web 浏览器窗口中。 Web 资源通常是 HTML 文档&#xff0c;但也可能是 PDF、图像、音频、视频或其他类型的内容。…

c语言的基础知识之结构体

目录前言结构体结构的自引用typedef函数结构体内存对齐修改默认对齐数位段什么是位段位段的内存分配位段的跨平台问题位段的意义以及应用枚举枚举常量的赋值枚举的优点总结前言 欢迎来到戴佳伟的小课堂&#xff0c;那今天我们讲啥呢&#xff1f; 问得好&#xff0c;我们今天要讲…

排好队,一个一个来:宫本武藏教你学队列(附各种队列源码)

文章目录前言&#xff1a;理解“队列”的正确姿势一个关于队列的小思考——请求处理队列的两大“护法”————顺序队列和链式队列数组实现的队列链表实现的队列循环队列关于开篇&#xff0c;你明白了吗&#xff1f;最后说一句前言&#xff1a; 哈喽&#xff01;欢迎来到黑洞晓…

Linux 线程基础

文章目录一、线程概念NPTL 介绍线程的本质线程共享与非共享资源线程的优缺点二、线程基础 API线程操作线程号线程的创建线程资源回收线程分离线程终止线程取消线程属性概述属性初始化和销毁分离状态线程栈地址线程栈大小综合参考程序线程使用注意事项一、线程概念 与进程&…