Bootstrap

OpenCV:在图像上绘制线段、矩形、圆形、椭圆、多边形以及添加文字

OpenCV:在图像上绘制线段、矩形、圆形、椭圆、多边形以及添加文字

import cv2
import numpy as np

'''绘制线段'''
def line_(img):
    h, w, _ = img.shape     #shape输出格式为[h, w, c]
    # print(img.shape, int(h/2), int(w/2))
    '''图像,起始坐标, 终点坐标, 线条颜色, 线条宽度(-1代表填充), 线条类型(此处使用默认:8型。另一种cv2.LINE_AA型绘画速度快,无明显差距)'''
    cv2.line(img, (0, int(h / 2)), (w, int(h / 2)), (0, 255, 255), 6)       #中间生成一条横线,int向下取整,不然会报错
    # cv2.line(img, (0, int(h / 2)), (w, int(h / 2)), (0, 255, 255), 6, cv2.LINE_AA)
    # cv2.imshow('line', img)

'''绘制矩形'''
def rectangle_(img):
    h, w, _ = img.shape
    '''图像,左上角坐标, 右下角坐标, 线条颜色, 线条宽度, 线条类型'''
    cv2.rectangle(img, (int(w / 4), int(3 * h / 4)), (int(3 * w / 4), int(h / 4)), (0, 255, 255), 5)      #坐标可自行更改
    # cv2.rectangle(img, (int(w / 4), int(3 * h / 4)), (int(3 * w / 4), int(h / 4)), (0, 255, 255), -1)
    # cv2.imshow('rectangle', img)

'''绘制圆形'''
def circle_(img):
    h, w, _ = img.shape
    '''图像,圆心坐标, 半径, 线条颜色, 线条宽度, 线条类型'''
    cv2.circle(img, (int(w / 2), int(h / 2)), int(w / 3), (0, 255, 255), 5)
    # cv2.circle(img, (int(w / 2), int(h / 2)), int(w / 3), (0, 255, 255), -1)
    # cv2.imshow('circle', img)

'''绘制椭圆'''
def ellipse_(img):
    h, w, _ = img.shape
    '''图像,圆心坐标, 长轴与短轴长度, 旋转角度(横轴逆时针旋转),起始角度(横轴逆时针旋转),终止角度,线条颜色, 线条宽度, 线条类型'''
    cv2.ellipse(img, (int(w / 2), int(h / 2)), (int(w / 2), int(h / 4)),  30, 0, 180, (0, 255, 255), 5)
    # cv2.ellipse(img, (int(w / 2), int(h / 2)), (int(w / 2), int(h / 4)),  30, 0, 180, (0, 255, 255),  -1)
    # cv2.imshow('ellipse', img)

'''绘制多边形'''
def polyline_(img):
    pts = np.array([[100,20], [150, 70], [30, 150], [0, 300]])
    pts = pts.reshape((-1, 1, 2))       #(-1, 行, 列),-1表示自行计算个数,行列大小按输入形式。
    # print(pts.shape)
    h, w, _ = img.shape
    '''图像,顶点坐标, 起与终点是否闭合(True闭合,False不闭合),线条颜色, 线条宽度, 线条类型'''
    cv2.polylines(img, [pts], True, (0, 0, 0), 5)
    # cv2.polylines(img, [pts], False, (0, 0, 0), 5)
    # cv2.imshow('polyline', img)

'''添加文字'''
def putText_(img):
    h, w, _ = img.shape
    '''图像,要显示的字,字左下角坐标,字体,字号(缩放比例),线条颜色, 线条宽度, 线条类型'''
    font = cv2.FONT_HERSHEY_SIMPLEX
    cv2.putText(img, 'YS', (int(w / 2), int(3 * h / 4)), font, 4, (0, 255, 255), 5)     #中文会显示为???
    # cv2.imshow('putText', img)



img = cv2.imread('可莉.png')
img = cv2.resize(img, [384, 683])       #修改的是[w, h]

'''挑选对应函数即可'''
line_(img)
rectangle_(img)
circle_(img)
ellipse_(img)
polyline_(img)
putText_(img)

cv2.imshow('images', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

在这里插入图片描述

参考
参考哔哩哔哩


;