opencv-015-绘制几何形状及随机数的生成

知识点

绘制几何形状

  • 绘制直线
  • 绘制圆
  • 绘制矩形
  • 绘制椭圆
  • 填充几何形状

OpenCV没有专门的填充方法,只是把绘制几何形状时候的线宽thickness参数值设置为负数即表示填充该几何形状或者使用参数CV_FILLED

随机数方法:
RNG 表示OpenCV C++版本中的随机数对象,rng.uniform(a, b)生成[a, b)之间的随机数,包含a,但是不包含b。

np.random.rand() 表示numpy中随机数生成,生成浮点数0~1的随机数, 包含0,不包含1。

代码(c++,python)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

/*
* 绘制几何形状及随机数
*/
int main() {
Mat image = Mat::zeros(Size(512, 512), CV_8UC3);
Rect rect(100, 100, 200, 200);
// 绘制
rectangle(image, rect, Scalar(255, 0, 0), 2, LINE_8, 0);
circle(image, Point(256, 256), 50, Scalar(0, 255, 0), 2, LINE_8, 0);
ellipse(image, Point(256, 256), Size(150, 50), 360, 0, 360, Scalar(0, 0, 255), 2, LINE_8, 0);
imshow("image_draw", image);
// 填充 thickness=-1 or FILLED
rectangle(image, rect, Scalar(255, 0, 0), FILLED, LINE_8, 0);
ellipse(image, Point(256, 256), Size(150, 50), 360, 0, 360, Scalar(0, 0, 255), FILLED, LINE_8, 0);
circle(image, Point(256, 256), 50, Scalar(0, 255, 0), -1, LINE_8, 0);
imshow("image_fill", image);

// 随机数
RNG rng(0xFFFFFF);
image.setTo(Scalar(0, 0, 0));
Mat image_copy = image.clone();
for (int i = 0; i < 100000; ++i) {
int x1 = rng.uniform(0, 512);
int y1 = rng.uniform(0, 512);
int x2 = rng.uniform(0, 512);
int y2 = rng.uniform(0, 512);

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

rect.x = x1;
rect.y = y1;
rect.width = x2 - x1;
rect.height = y2 - y1;
// LINE_AA 反锯齿
line(image, Point(x1, y1), Point(x2, y2), Scalar(b, g, r), 1, LINE_AA, 0);
rectangle(image_copy, rect, Scalar(b, g, r), 1, LINE_AA, 0);
imshow("image_line", image);
imshow("image_rect", image_copy);
char c = waitKey(20);
if (c == 27){
// ESC
break;
}
}

waitKey(0);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import cv2 as cv
import numpy as np

image = np.zeros((512, 512, 3), dtype=np.uint8)

cv.rectangle(image, (100, 100), (300, 300), (255, 0, 0), 2, cv.LINE_8, 0)
cv.circle(image, (256, 256), 50, (0, 0, 255), 2, cv.LINE_8, 0)
cv.ellipse(image, (256, 256), (150, 50), 360, 0, 360, (0, 255, 0), 2, cv.LINE_8, 0)
cv.imshow("image", image)
cv.waitKey(0)

for i in range(100000):
image[:,:,:]= 0
x1 = np.random.rand() * 512
y1 = np.random.rand() * 512
x2 = np.random.rand() * 512
y2 = np.random.rand() * 512

b = np.random.randint(0, 256)
g = np.random.randint(0, 256)
r = np.random.randint(0, 256)
# cv.line(image, (np.int(x1), np.int(y1)), (np.int(x2), np.int(y2)), (b, g, r), 4, cv.LINE_8, 0)
cv.rectangle(image, (np.int(x1), np.int(y1)), (np.int(x2), np.int(y2)), (b, g, r), 1, cv.LINE_8, 0)
cv.imshow("image", image)
c = cv.waitKey(20)
if c == 27:
break # ESC不


cv.imshow("image", image)
cv.waitKey(0)
cv.destroyAllWindows()

结果


代码地址

github