import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
# 封装图片显示函数
def image_show(image):
if image.ndim == 2:
plt.imshow(image, cmap='gray')
else:
image = cv.cvtColor(image, cv.COLOR_BGR2RGB)
plt.imshow(image)
plt.show()
if __name__ == '__main__':
# 读取原图
img_lenna = cv.imread('lenna.png')
img_lenna_copy = img_lenna.copy()
# 绘制直线
line_start = [10, 10] # 直线起始位置
line_end = [500, 500] # 直线终止位置
line_color = [255, 0, 0] # 设置直线颜色
line_width = 2 # 设置直线宽度
cv.line(img_lenna, line_start, line_end, line_color, line_width)
# 显示图片
image_show(img_lenna)
# 恢复图片
img_lenna = img_lenna_copy.copy()
# 绘制矩形
rec_start = [100, 100] # 矩形左上位置
rec_end = [400, 400] # 矩形右下位置
rec_color = [255, 255, 0] # 设置矩形颜色
rec_width = 2 # 设置矩形宽度
cv.rectangle(img_lenna, rec_start, rec_end, rec_color, rec_width)
# 显示图片
image_show(img_lenna)
# 恢复图片
img_lenna = img_lenna_copy.copy()
# 绘制圆形
circle_center = [250, 250] # 圆心位置
circle_radius = 100 # 半径长度
circle_color = [0, 255, 0] # 设置圆形颜色
circle_width = 2 # 设置圆形宽度
cv.circle(img_lenna, circle_center, circle_radius, circle_color, circle_width)
# 显示图片
image_show(img_lenna)
# 恢复图片
img_lenna = img_lenna_copy.copy()
# 绘制椭圆
ellipse_center = [250, 250] # 圆心位置
ellipse_axis = [400, 200] # 长轴和短轴
ellipse_angle = 30 # 倾斜角度
ellipse_color = [0, 0, 255] # 设置椭圆颜色
ellipse_width = 2 # 设置椭圆宽度
cv.ellipse(img_lenna, (ellipse_center, ellipse_axis, ellipse_angle), ellipse_color, ellipse_width)
# 显示图片
image_show(img_lenna)
# 恢复图片
img_lenna = img_lenna_copy.copy()
# 绘制多边形
poly_pts = np.array([[[100, 100]],
[[100, 200]],
[[300, 200]]]) # 多边形各顶点位置
poly_color = [0, 255, 255] # 设置多边形颜色
poly_width = 2 # 设置多边形宽度
cv.polylines(img_lenna, [poly_pts, poly_pts + 50], True, poly_color, poly_width)
# 显示图片
image_show(img_lenna)
# 恢复图片
img_lenna = img_lenna_copy.copy()
# 标注文字
text_str = "Lenna" # 标注的字符串
text_point = [30, 30] # 标注文字的位置
text_width = 1.0 # 标注文字的大小
text_color = [0, 0, 255] # 设置文字的颜色
cv.putText(img_lenna, text_str, text_point, cv.FONT_HERSHEY_COMPLEX, text_width, text_color)
# 显示图片
image_show(img_lenna)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)