图像中不规则物体的长轴与短轴: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.")
相关推荐
浠寒AI1 小时前
智能体模式篇(上)- 深入 ReAct:LangGraph构建能自主思考与行动的 AI
人工智能·python
weixin_505154462 小时前
数字孪生在建设智慧城市中可以起到哪些作用或帮助?
大数据·人工智能·智慧城市·数字孪生·数据可视化
Best_Me072 小时前
深度学习模块缝合
人工智能·深度学习
YuTaoShao2 小时前
【论文阅读】YOLOv8在单目下视多车目标检测中的应用
人工智能·yolo·目标检测
算家计算2 小时前
字节开源代码模型——Seed-Coder 本地部署教程,模型自驱动数据筛选,让每行代码都精准落位!
人工智能·开源
伪_装2 小时前
大语言模型(LLM)面试问题集
人工智能·语言模型·自然语言处理
gs801403 小时前
Tavily 技术详解:为大模型提供实时搜索增强的利器
人工智能·rag
music&movie3 小时前
算法工程师认知水平要求总结
人工智能·算法
量子位3 小时前
苹果炮轰推理模型全是假思考!4 个游戏戳破神话,o3/DeepSeek 高难度全崩溃
人工智能·deepseek
黑鹿0223 小时前
机器学习基础(四) 决策树
人工智能·决策树·机器学习