项目功能实现:在原图上进行每隔0.5s随机绘制不同长度不同颜色的线段(保存之前的线段),在另一个画布上进行绘制随机不同长度不同颜色的线段(不保存之前的线段)
按照之前的博文结构来,这里就不在赘述了
一、头文件
random.h
#pragma once#include<opencv2/opencv.hpp>using namespace cv;class RANDOM {
public:void random(Mat& image);
};#pragma once
二、函数实现
random.cpp
Mat canvas = Mat::zeros(Size(512, 512), CV_8UC3);
定义一个全黑的大小为512*512的画布canvas
RNG rng(990522);
根据电脑系统的时钟进行设置随机种子
high = canvas.rows;wide = canvas.cols;
获取画布的高和宽
x1 = rng.uniform(0, wide);
在0和wide之间随机取值
其他的均类似
canvas = Scalar(0, 0, 0);
因为每次画布上的线段都不保存,故每次循环都要对其进行初始化
line(canvas, Point(x1, y1), Point(x2, y2), Scalar(b, g, r), 1, LINE_AA, 0);
之后才进行绘制,该函数详细说明可参考博文:十四、图像几何形状绘制
参数一:要操作的图片对象
参数二:初始位置
参数三:最终位置
参数四:线条颜色
参数五:线条粗细
参数六:绘制线条时会出现锯齿,对其进行优化,等价于16,对周围16个像素点进行调优
参数七:微调相当于一个偏置项
line(image, Point(x1, y1), Point(x2, y2), Scalar(b, g, r), 1, LINE_AA, 0);
原图保存之前的线段,故可以直接绘制即可
#include"random.h"
#include<iostream>
#include<opencv2/opencv.hpp>void RANDOM::random(Mat& image) {Mat canvas = Mat::zeros(Size(512, 512), CV_8UC3);RNG rng(990522);int high, wide;high = canvas.rows;wide = canvas.cols;int x1, x2, y1, y2,b, g, r;while(true) {int c = waitKey(500);if (c == 27) {break;}x1 = rng.uniform(0, wide);y1 = rng.uniform(0, high);x2 = rng.uniform(0, wide);y2 = rng.uniform(0, high);b = rng.uniform(0, 255);g = rng.uniform(0, 255);r = rng.uniform(0, 255);canvas = Scalar(0, 0, 0);line(canvas, Point(x1, y1), Point(x2, y2), Scalar(b, g, r), 1, LINE_AA, 0);line(image, Point(x1, y1), Point(x2, y2), Scalar(b, g, r), 1, LINE_AA, 0);imshow("random_drawing", canvas);imshow("image_drawing", image);}
}
三、主函数
yy_main.cpp
#include <opencv2/opencv.hpp>
#include <iostream>
#include "random.h"using namespace cv;
using namespace std;int main(int argc, char** argv) {Mat src = cv::imread("E:/C++_workspace/beyond.jpg", IMREAD_COLOR);if (src.empty()) {printf("load image is false...\n");return -1;}namedWindow("yanyu", WINDOW_FREERATIO);imshow("yanyu", src);RANDOM yy;yy.random(src);waitKey(0);destroyAllWindows();return 0;
}
项目结构如下:
效果图如下:
四、课后作业
项目功能实现:在原图上进行每隔0.5s随机绘制不同长度不同颜色的线段(不保存之前的线段),在另一个画布上进行绘制随机不同长度不同颜色的线段(保存之前的线段)
random.cpp
和之前的功能效果刚好相反
beyond = image.clone();
这里只需要对原图克隆一下,每次绘制线段的时候都在原始图像上进行绘制,绘制之前都要进行初始化
同时因为画布要保存之前的线段,把初始化操作canvas = Scalar(0, 0, 0);
去掉即可
代码如下:
#include"random.h"
#include<iostream>
#include<opencv2/opencv.hpp>void RANDOM::random(Mat& image) {Mat canvas = Mat::zeros(Size(512, 512), CV_8UC3);Mat beyond;RNG rng(990522);int high, wide;high = canvas.rows;wide = canvas.cols;int x1, x2, y1, y2,b, g, r;while(true) {int c = waitKey(500);if (c == 27) {break;}x1 = rng.uniform(0, wide);y1 = rng.uniform(0, high);x2 = rng.uniform(0, wide);y2 = rng.uniform(0, high);b = rng.uniform(0, 255);g = rng.uniform(0, 255);r = rng.uniform(0, 255);line(canvas, Point(x1, y1), Point(x2, y2), Scalar(b, g, r), 1, LINE_AA, 0);beyond = image.clone();line(beyond, Point(x1, y1), Point(x2, y2), Scalar(b, g, r), 1, LINE_AA, 0);imshow("random_drawing", canvas);imshow("image_drawing", beyond);}
}
效果图如下: