最近刷抖音的時候發(fā)現(xiàn)一些圖片轉(zhuǎn)字符畫的視頻(如下圖這樣的)
AFF9147F9ABAC25EF450B2DF5225EFB1.png
(網(wǎng)上也有在線工具祭芦,百度搜索圖片轉(zhuǎn)字符畫可以搜索到)
乍一看 哇塞,好厲害仍翰,想了想其中的原理發(fā)現(xiàn)其實并沒有多難赫粥。正好最近在學習C和C++,于是乎準備編程來實現(xiàn)予借。
首先找到這樣一段ASCII字符
@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`'.
原理
這段ASCII字符是用來形容每個像素點的顏色深淺越平,從視覺效果(灰度)來看,字符的越復(fù)雜越能形容深色灵迫,我們只需要獲得一張圖并將這張圖轉(zhuǎn)化為灰度圖秦叛,然后遍歷其中的像素點的灰度值,并根據(jù)灰度值轉(zhuǎn)化為相應(yīng)的ASCII字符瀑粥,最后存入一個txt文件中即可挣跋。
(注:使用windows的記事本打開時,需要將自動換行關(guān)閉狞换,將字體改為宋體避咆,大小小于4號才能看出效果)
然后開始編碼
這里使用到了OpenCV庫,主要用來做一些圖片的轉(zhuǎn)化修噪,當然也可以使用別的方法來轉(zhuǎn)換查库。
主要代碼:
Mat srcImg = imread(imgFileName); //讀取一張圖片
Mat grayImg;
cvtColor(srcImg, grayImg, COLOR_RGB2GRAY);//將圖片轉(zhuǎn)成灰度圖
string str; //定義一個用來存儲圖片轉(zhuǎn)換的字符的字符串
//循環(huán)遍歷(灰度圖)圖片的每一個像素點
for(int y = 0; y < grayImg.rows; y++) {
for (int x = 0; x < grayImg.cols; x++) {
int grayVal = (int)grayImg.at<uchar>(y, x);
//獲取每個像素點的灰度值,并根據(jù)灰度值對應(yīng)ASCII字符數(shù)組中的的字符
//這里的69是定義的ASCII字符數(shù)組的長度割按,我直接寫了
int index = 69 / 255.0 * grayVal;
str += codeLib[index];
}
str += "\r\n";
}
完整代碼
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <string.h>
#include <fstream>
using namespace std;
using namespace cv;
void showImage(const char *winName, InputArray imgMat, int x, int y);
void outToFile(const char *fileName, const string content);
const char codeLib[] = "@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\"^`'. ";
const char *imgFileName = "20161023140920353.jpg";
const char *outFileName = "test.txt";
int main() {
cout << strlen(codeLib) << " : " << codeLib << endl;
Mat srcImg = imread(imgFileName);
Mat grayImg;
cvtColor(srcImg, grayImg, COLOR_RGB2GRAY);
string str;
for(int y = 0; y < grayImg.rows; y++) {
for (int x = 0; x < grayImg.cols; x++) {
int grayVal = (int)grayImg.at<uchar>(y, x);
// cout << grayVal << endl;
int index = 69.0 / 255.0 * grayVal;
str += codeLib[index];
}
str += "\r\n";
}
cout << str << endl;
outToFile(outFileName, str);
showImage("src", srcImg, 0, 0);
showImage("gray", grayImg, 100, 100);
waitKey(0);
return 0;
}
//顯示圖片
void showImage(const char *winName, InputArray imgMat, int x, int y){
namedWindow(winName, WINDOW_AUTOSIZE);
moveWindow(winName
, x, y);
imshow(winName, imgMat);
}
//將字符串寫入文件
void outToFile(const char *fileName, const string content){
ofstream outStream;
outStream.open(fileName);
outStream << content << endl;
outStream.close();
}
結(jié)果
原圖:
20161023140920353.jpg
結(jié)果:
20180608112935.png