15 随机数与随机颜色

15 随机数与随机颜色

opencv知识点:

  • 随机数 - RNG
  • 线段绘制 - line()

本课所解决的问题:

  • 如何在绘制图形中利用到随机数?

1.利用随机数设置坐标与颜色

我们绘制一个线段,把两个点的坐标,还有三个通道的颜色都设置为了随机数得到

//函数定义
void randow_drawing();

//函数实现
void QuickDemo::randow_drawing() {

	Mat canvas = Mat::zeros(Size(512, 512), CV_8UC3);

	int w = canvas.cols;
	int h = canvas.rows;

	RNG rng(5465);//我们随便输入1个数作为种子

	while (true) {

		int c = waitKey(10);
		if (c == 27) {//退出
			break;
		}
		
		int x1 = rng.uniform(0, w);
		int y1 = rng.uniform(0, h);
		int x2 = rng.uniform(0, w);
		int y2 = rng.uniform(0, h);

		int b = rng.uniform(0, 255);
		int g = rng.uniform(0, 255);
		int r = rng.uniform(0, 255);

		line(canvas, Point(x1, y1), Point(x2, y2), Scalar(b, g, r), 1, 8, 0);
		imshow("随机线段", canvas);
	}
}

详细的程序

main.cpp

#include "opencv2/opencv.hpp"
#include "quickopencv.h"
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, char** argv) {
	Mat src = imread("C:/Users/LZQ/Desktop/lena.png"); //  B, G, R
	if (src.empty()) {
		printf("could not load image....\n");
		return -1;
	}

	imshow("输入窗口", src);

	QuickDemo qd;

	qd.random_drawing(); 



	waitKey(0);
	destroyAllWindows();
	return 0;
}

quickdemo.cpp

void QuickDemo::random_drawing() {

	Mat canvas = Mat::zeros(Size(512, 512), CV_8UC3);

	int w = canvas.cols;
	int h = canvas.rows;

	RNG rng(5465);                    //我们随便输入1个数作为种子

	while (true) {

		int c = waitKey(10);
		if (c == 27) {                       //退出
			break;
		}

		int x1 = rng.uniform(0, w);
		int y1 = rng.uniform(0, h);
		int x2 = rng.uniform(0, w);
		int y2 = rng.uniform(0, h);

		int b = rng.uniform(0, 255);
		int g = rng.uniform(0, 255);
		int r = rng.uniform(0, 255);

		line(canvas, Point(x1, y1), Point(x2, y2), Scalar(b, g, r), 1, 8, 0);
		imshow("随机线段", canvas);
	}
}

quickopencv.h

#pragma once

#include <opencv2/opencv.hpp>

using namespace cv;

class QuickDemo {            //快速的演示文件 class类
public:

	void random_drawing();  //15

};

结果

4c369e94f3a1cf98124b24f7afc64c7

443d00661c13b311c10bb27f98d4a10

本课所用API查阅

RNG

RNG(Random Number Generator,随机数生成器)是opencv中的一个随机数生成器类
uniform是RNG中的一个方法,uniform(a,b),指定数的范围为(a,b)

line()

posted @ 2023-01-13 15:06  L707  阅读(91)  评论(0编辑  收藏  举报