C++Opencv method for implementing console character animation

  • 2020-10-23 20:14:15
  • OfStack

The principle of overview

First, opencv is used to get the color of specific pixels in the image
Select different characters according to the color range
Then print at a specific location in the console
The point is to get the color of the pixels

Gets the color image load variable for a pixel in the image

You can use the Mat type in opencv to store images


Mat img;
img = imread(" Image path ");

Convert the image to grayscale

Why change the image to grayscale?
Mainly to make the picture color sheet 1
Reduce the amount of work required to determine the latter conditions
But you don't have to do this one step


Mat gimg;
//img Convert to grayscale and output to gimg In the 
cvtColor(img, gimg, CV_BGR2GRAY);

Gets the color of a pixel in an image

A new variable type, Scalar, is required to store the 1 value


Scalar color = gimg.at<uchar>(row, col);
// If the image is not grayscale it can be uchar Instead of Vec3b

(row,col) is the coordinate point where the pixel is located
You can use 1 nested loop to get color for all pixels
You can select an appropriate data structure to store all the values retrieved
Scalar type has four parameters, Scalar (B G, R, alpha)
color[0],color[1]... color[3] visits specific values
Maximum value of B,G,R is 255
That's where the most important part is

Moves the console cursor to the specified coordinates

It is not recommended to use this method, which will reduce the printing speed to a certain extent and affect the operation effect. It is recommended to use appropriate data structure to access the relevant information of pixel points obtained in advance sequentially
This method moves the console cursor to the specified location (not recommended)


#include<Windows.h>
void gotoxy(int x, int y)
{
	COORD pos;
	pos.X = x;
	pos.Y = y;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}

conclusion

The main approach is the above content, the specific logic and code optimization can be arranged
The header file you need


#include <opencv2\opencv.hpp>
#include <opencv2\imgproc\types_c.h>
#include <iostream>

Related articles: