利用open CV检测图片中的直线,圆形,三角形
时间: 2023-05-24 18:07:19 浏览: 92
以下是用Python和OpenCV库检测图片中直线、圆形和三角形的示例代码:
```Python
import cv2
import numpy as np
# 读取图片
img = cv2.imread('test.jpg')
# 转为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 高斯模糊
blur = cv2.GaussianBlur(gray, (5, 5), 0)
# 边缘检测
edges = cv2.Canny(blur, 50, 150, apertureSize=3)
# 直线检测
lines = cv2.HoughLinesP(edges, 1, np.pi/180, 100, minLineLength=10, maxLineGap=10)
# 绘制直线
for line in lines:
x1, y1, x2, y2 = line[0]
cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
# 圆形检测
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0)
# 绘制圆形
if circles is not None:
circles = np.uint16(np.around(circles))
for circle in circles[0, :]:
cv2.circle(img, (circle[0], circle[1]), circle[2], (0, 0, 255), 2)
# 三角形检测
contours, _ = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
approx = cv2.approxPolyDP(contour, 0.01 * cv2.arcLength(contour, True), True)
if len(approx) == 3:
cv2.drawContours(img, [approx], 0, (255, 0, 0), 2)
# 显示图片
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
该代码首先读取一张图片,然后将其转换为灰度图,并进行高斯模糊和边缘检测。接下来,使用Hough变换在边缘图像中检测直线和圆形,并分别绘制在原图上。最后,使用findContours函数在边缘图像中寻找轮廓,并使用approxPolyDP函数判断是否为三角形,并将其绘制在原图上。
阅读全文