在图像上绘制线段,矩形,圆,椭圆,文字。
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace std;
using namespace cv;
Mat src; //全局变量
string drawdemo = "draw line to img demo";
void Myline(); //画线段
void MyRectangle(); //画矩形框
void Mycircle(); //画圆
void Myellipse(); //画椭圆
void Myputtext(); //写字
int main(){
src = imread("/Users/ming/Documents/test.jpg");
// cvtColor(src, src, CV_BGR2GRAY);
if (! src.data){
printf("cannot load image ...");
}
// namedWindow("src img", CV_WINDOW_AUTOSIZE);
// imshow("src img", src);
Myline();
MyRectangle();
Mycircle();
Myellipse();
Myputtext();
namedWindow(drawdemo, CV_WINDOW_AUTOSIZE);
imshow(drawdemo, src);
waitKey(0);
return 0;
}
void Myline(){
Point p1, p2;
Scalar color;
p1 = Point(20, 60); //线的始点
p2 = Point(100, 200); //线的终点
// p2.x = 200;
// p2.y = 300;
color = Scalar(0, 0, 255);
line(src, p1, p2, color);
}
void MyRectangle(){
Rect rect;
rect = Rect(100, 200, 50, 25); //矩形起点x,起点y,宽,高
Scalar color = Scalar(255, 0, 0);
rectangle(src, rect, color);
}
void Mycircle(){
Point p = Point(320, 190); //圆的中心点
int r= 50; //圆的半径
Scalar color = Scalar(0, 255, 0);
circle(src, p, r, color);
}
void Myellipse(){
Point p = Point(src.rows/2, src.cols/2); //椭圆中心点
Size axis = Size(50, 100); //长轴,短轴大小
Scalar color = Scalar(127, 0, 127); //颜色
double angle = 30, startangle = 0, endangle = 180;
ellipse(src, p, axis, angle, startangle, endangle, color); //画椭圆
}
void Myputtext(){
string text = "put text on image";
Point p = Point(200, 140);
int fontface = CV_FONT_NORMAL; //字体类型
cout << fontface << endl ;
double fontscale = 1.2; // 尺寸因子,值越大文字越大
Scalar color = Scalar(0, 0, 255);
putText(src, text, p, fontface, fontscale, color);
// putText(<#cv::InputOutputArray img#>, <#const cv::String &text#>, <#cv::Point org#>, <#int fontFace#>, <#double fontScale#>, <#cv::Scalar color#>)
}
在黑色背景图上随机画线,颜色位置随机变化,用
RNG rng;
rng.uniform(0, width)产生随机数 //索引是从0开始,要小心
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace std;
using namespace cv;
void random_line();
Mat img;
int main(){
// img = Mat::zeros(400, 500, CV_8UC3); //新建黑色背景图1
img.create(400, 500, CV_8UC3);
img = Scalar(0, 0, 0); //新建黑色背景图2
// cout << img.channels() << endl;
random_line(); //画随机线条
// imshow("empty", img);
// waitKey(0);
return 0;
}
void random_line(){
int height = img.rows;
int width = img.cols;
Point start_point, end_point;
RNG rng; //RNG为随机数生成器
for (int i = 0; i < 1000 ; i++){
start_point = Point(rng.uniform(0, width), rng.uniform(0, height)); //索引是从0开始,要小心
// start_point = Point(0, 0);
end_point = Point(rng.uniform(0, width), rng.uniform(0, height));
cout << "start point:" << start_point;
cout << "end point:" << end_point;
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
line(img, start_point, end_point, color);
namedWindow("random line img", CV_WINDOW_AUTOSIZE);
imshow("random line img", img);
if (waitKey(30) > 0){
break;
}
}
}