用python写一个使用opencv来辨别红圆环和绿圆环的代码
时间: 2023-02-24 19:32:30 浏览: 179
好的,以下是使用 OpenCV 识别红圆环和绿圆环的 Python 代码:
```
import cv2
import numpy as np
# 读取图片
img = cv2.imread("input.jpg")
# 将图片转换为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 通过阈值化处理,得到二值图
_, thresh = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY_INV)
# 检测圆
circles = cv2.HoughCircles(thresh, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0)
# 如果检测到圆,遍历每一个圆
if circles is not None:
circles = np.round(circles[0, :]).astype("int")
for (x, y, r) in circles:
# 画出圆的位置
cv2.circle(img, (x, y), r, (0, 255, 0), 4)
# 画出圆心
cv2.rectangle(img, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
# 显示图片
cv2.imshow("detected circles", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
上述代码使用 HoughCircles 函数来检测圆,并在图片上画出圆的位置和圆心。如果需要识别红圆环和绿圆环,可以对检测到的圆进行颜色判断,以确定是红圆环还是绿圆环。
阅读全文
相关推荐







