图像中不规则物体的长轴与短轴:OpenCV实现指南

1.首先,读取图像并将其转换为灰度图像。

2.进行图像预处理,包括使用高斯模糊和阈值化,以便更好地处理图像。

3.通过使用OpenCV的cv2.findContours()函数,找到图像中的所有轮廓。

4.遍历所有轮廓,如果轮廓点的数量大于等于5个,则将这个轮廓拟合为一个椭圆。

5.如果成功拟合出椭圆,则获取椭圆的中心坐标、长轴长度、短轴长度和旋转角度。

6.使用计算得到的椭圆信息,计算出长轴和短轴的端点坐标。

7.使用OpenCV的cv2.ellipse()函数在原始图像上绘制椭圆,并使用cv2.circle()函数在图像上绘制长轴和短轴的四个端点,并分别用红色和蓝色表示。

8.最后,显示带有椭圆和端点的图像,等待用户按下任意键后关闭显示窗口。

python 复制代码
import cv2
import numpy as np

image = cv2.imread("XXX.png", cv2.IMREAD_GRAYSCALE)
blur = cv2.GaussianBlur(image, (5, 5), 0)
_, thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

ellipse = None
for contour in contours:
    if len(contour) >= 5:
        ellipse = cv2.fitEllipse(contour)
        break

if ellipse is not None:
    center, axes, angle = ellipse
    major_axis, minor_axis = axes
    angle_rad = np.deg2rad(angle)
    cos_angle = np.cos(angle_rad)
    sin_angle = np.sin(angle_rad)

    # 长轴端点坐标
    x1 = int(center[0] + major_axis / 2 * cos_angle)
    y1 = int(center[1] - major_axis / 2 * sin_angle)
    x2 = int(center[0] - major_axis / 2 * cos_angle)
    y2 = int(center[1] + major_axis / 2 * sin_angle)

    # 短轴端点坐标
    x3 = int(center[0] + minor_axis / 2 * sin_angle)
    y3 = int(center[1] + minor_axis / 2 * cos_angle)
    x4 = int(center[0] - minor_axis / 2 * sin_angle)
    y4 = int(center[1] - minor_axis / 2 * cos_angle)

    # 在图像上绘制椭圆及长轴和短轴的端点
    image_with_ellipse = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
    cv2.ellipse(image_with_ellipse, ellipse, (0, 255, 0), 2)
    cv2.circle(image_with_ellipse, (x1, y1), 5, (0, 0, 255), -1)  # 长轴端点用红色标记
    cv2.circle(image_with_ellipse, (x2, y2), 5, (0, 0, 255), -1)  # 长轴端点用红色标记
    cv2.circle(image_with_ellipse, (x3, y3), 5, (255, 0, 0), -1)  # 短轴端点用蓝色标记
    cv2.circle(image_with_ellipse, (x4, y4), 5, (255, 0, 0), -1)  # 短轴端点用蓝色标记

    # 显示图像
    cv2.imshow("Image with Ellipse and Axes", image_with_ellipse)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
else:
    print("No ellipse found.")
相关推荐
风象南2 小时前
我把大脑开源给了AI
人工智能·后端
Johny_Zhao4 小时前
OpenClaw安装部署教程
linux·人工智能·ai·云计算·系统运维·openclaw
飞哥数智坊4 小时前
我帮你读《一人公司(OPC)发展研究》
人工智能
冬奇Lab7 小时前
OpenClaw 源码精读(3):Agent 执行引擎——AI 如何「思考」并与真实世界交互?
人工智能·aigc
没事勤琢磨9 小时前
如何让 OpenClaw 控制使用浏览器:让 AI 像真人一样操控你的浏览器
人工智能
用户5191495848459 小时前
CrushFTP 认证绕过漏洞利用工具 (CVE-2024-4040)
人工智能·aigc
牛马摆渡人5289 小时前
OpenClaw实战--Day1: 本地化
人工智能
前端小豆9 小时前
玩转 OpenClaw:打造你的私有 AI 助手网关
人工智能
BugShare10 小时前
写一个你自己的Agent Skills
人工智能·程序员
机器之心10 小时前
英伟达护城河被AI攻破,字节清华CUDA Agent,让人人能搓CUDA内核
人工智能·openai