以下是一个简单的Python代码,用于识别三角形、四边形、多边形和圆形的几何形状:

import cv2
import numpy as np

def detect_shape(contour):
    perimeter = cv2.arcLength(contour, True)
    approx = cv2.approxPolyDP(contour, 0.04 * perimeter, True)

    if len(approx) == 3:
        return 'Triangle'
    elif len(approx) == 4:
        x, y, w, h = cv2.boundingRect(approx)
        aspectRatio = float(w)/h
        if aspectRatio >= 0.95 and aspectRatio <= 1.05:
            return 'Square'
        else:
            return 'Rectangle'
    elif len(approx) > 4:
        return 'Polygon'
    else:
        return 'Circle'

def main():
    image = cv2.imread('shapes.jpg')
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    edges = cv2.Canny(blurred, 50, 150)

    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    for contour in contours:
        shape = detect_shape(contour)
        cv2.drawContours(image, [contour], -1, (0, 255, 0), 2)
        x, y = contour[0][0]
        cv2.putText(image, shape, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)

    cv2.imshow('Shape Detection', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

if __name__ == '__main__':
    main()

注意事项:

  1. 代码中使用的输入图像为名为shapes.jpg的图像文件,你可以将其替换为你自己的图像文件。
  2. 代码使用OpenCV库进行图像处理和轮廓检测,因此需要在你的环境中安装OpenCV库。
  3. 该代码使用Canny边缘检测和多边形逼近来识别几何形状。你可以根据实际需求进行调整和改进。

原文地址: http://www.cveoy.top/t/topic/o2IS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录