美文网首页
015 几何形状绘制

015 几何形状绘制

作者: 几时见得清梦 | 来源:发表于2019-08-15 23:52 被阅读0次
  1. 几何形状绘制
  • 绘制直线
  • 绘制圆
  • 绘制矩形
  • 绘制椭圆
  1. 填充几何形状
  • OpenCV没有专门的填充方法,只是把绘制几何形状时候的线宽 - thickness参数值设置为负数即表示填充该几何形状,或者使用参数CV_FILLED
  1. 随机数方法:
  • RNG 表示OpenCV C++版本中的随机数对象,rng.uniform(a, b)生成[a, b)之间的随机数,包含a,但是不包含b。
  • np.random.rand() 表示numpy中随机数生成,生成浮点数0~1的随机数, 包含0,不包含1。
几何形状的绘制和填充
重复生成直线的结果
重复生成矩形的结果

C++

#include<opencv2/opencv.hpp>
#include<iostream>

using namespace cv;
using namespace std;

int main(int argc, char** argv) {
    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, 0, 255), 2, LINE_8, 0);
    ellipse(image, Point(256, 256), Size(150, 50), 360, 0, 360, Scalar(0, 255, 0), 2, LINE_8, 0);
    imshow("image", image);
    waitKey(0);

    RNG rng(0xFFFFFF);
    image.setTo(Scalar(0, 0, 0));

    for (int i = 0; i < 100000; i++) {
        // image.setTo(Scalar(0, 0, 0));
        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);
        line(image, Point(x1, y1), Point(x2, y2), Scalar(b, g, r), 1, LINE_AA, 0);
        rect.x = x1;
        rect.y = y1;
        rect.width = x2 - x1;
        rect.height = y2 - y1;
        // rectangle(image, rect, Scalar(b, g, r), 1, LINE_AA, 0);
        imshow("image", image);
        char c = waitKey(20);
        if (c == 27)
            break;

        imshow("image", image);
    }
    waitKey(0);
    return 0;
}

Python

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.LINE_8表示绘制时采用8邻域填充
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()

相关文章

网友评论

      本文标题:015 几何形状绘制

      本文链接:https://www.haomeiwen.com/subject/lilxsctx.html