图像中不规则物体的长轴与短轴: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.")
相关推荐
静心问道15 分钟前
TrOCR: 基于Transformer的光学字符识别方法,使用预训练模型
人工智能·深度学习·transformer·多模态
说私域17 分钟前
基于开源AI大模型、AI智能名片与S2B2C商城小程序源码的用户价值引导与核心用户沉淀策略研究
人工智能·开源
亲持红叶18 分钟前
GLU 变种:ReGLU 、 GEGLU 、 SwiGLU
人工智能·深度学习·神经网络·激活函数
说私域18 分钟前
线上协同办公时代:以开源AI大模型等工具培养网感,拥抱职业变革
人工智能·开源
群联云防护小杜20 分钟前
深度隐匿源IP:高防+群联AI云防护防绕过实战
运维·服务器·前端·网络·人工智能·网络协议·tcp/ip
摘星编程25 分钟前
构建智能客服Agent:从需求分析到生产部署
人工智能·需求分析·智能客服·agent开发·生产部署
不爱学习的YY酱28 分钟前
信息检索革命:Perplexica+cpolar打造你的专属智能搜索中枢
人工智能
whaosoft-1432 小时前
51c自动驾驶~合集7
人工智能
刘晓倩5 小时前
Coze智能体开发实战-多Agent综合实战
人工智能·coze
石迹耿千秋6 小时前
迁移学习--基于torchvision中VGG16模型的实战
人工智能·pytorch·机器学习·迁移学习