图像中不规则物体的长轴与短轴: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.")
相关推荐
ar01236 分钟前
可视化特点在AR远程协助方面的重要意义
人工智能·ar
AnalogElectronic2 小时前
人工智能初级工程师认证复习纲要(高频重点标记)
人工智能
前端不太难2 小时前
AI 原生架构:鸿蒙App的下一代形态
人工智能·架构·harmonyos
Fzuim2 小时前
从 LLM 接口到 Agent 接口:AI 融合系统的架构演进与未来趋势分析报告
人工智能·ai·重构·架构·agent·runtime
GISer_Jing9 小时前
AI自动化工作流:智能驱动未来(升级研究生项目!!!)
人工智能·前端框架·自动化
草捏子9 小时前
Agent Skills:让 AI 一次学会、永远记住的能力扩展方案
人工智能
NocoBase9 小时前
【2.0 教程】第 1 章:认识 NocoBase ,5 分钟跑起来
数据库·人工智能·开源·github·无代码
后端小肥肠9 小时前
OpenClaw实战|从识图到公众号内容自动化,我跑通了完整链路
人工智能·aigc·agent
Elastic 中国社区官方博客9 小时前
快速 vs. 准确:衡量量化向量搜索的召回率
大数据·人工智能·elasticsearch·搜索引擎·ai·全文检索
qq_381338509 小时前
【技术日报】2026-03-18 AI 领域重磅速递
大数据·人工智能