
本文演示如何利用OpenCV库,根据给定的矩形坐标,绘制矩形并标注其九个关键点(左上、上中、右上、左中、中心、右中、左下、下中、右下)。
假设矩形的左(left)、上(top)、右(right)、下(bottom)坐标分别为530, 836, 685, 885。我们将基于这些坐标计算九个关键点的坐标,并在图像上用圆圈标记。同时,绘制包含这些点的矩形。
关键在于理解坐标系并计算矩形内关键点的坐标。矩形的左上角为(left, top),右下角为(right, bottom)。通过简单的算术运算即可计算其他关键点坐标。例如,中心点坐标为((left + right) // 2, (top + bottom) // 2),上中点坐标为((left + right) // 2, top),以此类推。
以下Python代码使用OpenCV实现此功能:
import cv2
import numpy as np
# 创建一个1000x1000的白色图像
img = np.ones((1000, 1000), np.uint8) * 255
# 矩形坐标
left, top, right, bottom = 530, 836, 685, 885
# 绘制矩形
cv2.rectangle(img, (left, top), (right, bottom), (0, 0, 0), 2) # 使用黑色线条,厚度为2
# 计算并绘制九个关键点
center_x = (left + right) // 2
center_y = (top + bottom) // 2
points = [
(left, top), # 左上
(center_x, top), # 上中
(right, top), # 右上
(left, center_y), # 左中
(center_x, center_y), # 中心
(right, center_y), # 右中
(left, bottom), # 左下
(center_x, bottom), # 下中
(right, bottom) # 右下
]
for x, y in points:
cv2.circle(img, (x, y), 5, (0, 0, 255), cv2.FILLED) # 使用红色填充圆圈,半径为5
# 显示图像
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()代码首先创建一个白色图像,然后绘制黑色矩形。之后,它计算九个关键点的坐标,并在每个点绘制一个红色填充圆圈。最后,它显示图像,并等待用户按键关闭窗口。 代码更清晰地展现了关键点的计算过程,并对绘制参数进行了微调,使结果更易于理解和观察。
以上就是如何用OpenCV绘制矩形及其九个关键点?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号