Last active
April 30, 2020 19:59
-
-
Save furkantektas/0e049fd419c3a1ed9f04 to your computer and use it in GitHub Desktop.
OpenCV Overlay Text on Stream
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Standard C++ Libraries | |
#include <iostream> | |
#include <sstream> | |
#include <string> | |
#include <opencv2/core/core.hpp> | |
#include <opencv2/imgproc/imgproc.hpp> | |
#include <opencv2/highgui/highgui.hpp> | |
using std::cout; | |
using std::endl; | |
using namespace cv; | |
#define BOXSIZE 50 | |
string text = "Lorem Ipsum Dolor Sit Amet"; | |
cv::Point getPt1(Mat& frame) { | |
return cv::Point(frame.cols,frame.rows-BOXSIZE); | |
} | |
cv::Point getPt2(Mat& frame) { | |
return cv::Point(0,frame.rows); | |
} | |
void drawRectangle (Mat& frame) { | |
static cv::Point pt1(getPt1(frame)); | |
static cv::Point pt2(getPt2(frame)); | |
static cv::Scalar white(0,0,0); | |
Mat overlay; | |
frame.copyTo(overlay); | |
cv::rectangle( | |
overlay, | |
pt1, | |
pt2, | |
white, | |
CV_FILLED | |
); | |
double opacity = 0.6; | |
addWeighted(overlay, opacity, frame, 1 - opacity, 0, frame); | |
} | |
void drawText(Mat& frame) { | |
int baseline=0; | |
const int fontFace = CV_FONT_HERSHEY_SIMPLEX; | |
const double fontScale = 1; | |
const int thickness = 1; | |
static Size textSize = getTextSize(text, fontFace, | |
fontScale, thickness, &baseline); | |
static Point textOrg((getPt1(frame).x - getPt2(frame).x)/2-textSize.width/2, (getPt1(frame).y + getPt2(frame).y)/2+textSize.height/2); | |
putText(frame, text, textOrg, fontFace, fontScale, | |
Scalar::all(255), thickness, 8); | |
} | |
int main(int argc, char *argv[]) | |
{ | |
Mat frame; | |
namedWindow("video", 1); | |
VideoCapture cap(argv[1]); | |
cap >> frame; | |
while ( cap.isOpened() ) | |
{ | |
cap >> frame; | |
if(frame.empty()) break; | |
drawRectangle(frame); | |
drawText(frame); | |
imshow("video", frame); | |
if(waitKey(30) >= 0) break; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment