使用 OpenCV 霍夫變換-圓檢測(cè),對(duì)周圍背景比較敏感,容易誤識(shí)別,不受控。若你也有此困惑,建議試試本文中的方法,識(shí)別效果佳,能夠很好地排除類圓矩形的干擾,話不多說直接上代碼。
代碼
一、實(shí)現(xiàn)類
import math
import cv2
class CircleDetector(object):
'''
Parameters
----------
img: ndarray
A color image.
threshold: int or float
Image binary threshold.
minRadius: int or float
Minimum value of circle radius.
maxRadius: int or flaot
Maximum value of circle radius.
Returns
-------
A tuple of (center(x, y), size(w, h), angle)
'''
def detectCircles(self, image, threshold, minRadius, maxRadius):
circles = list()
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur_image = cv2.GaussianBlur(gray_image, (5, 5), 0)
ret, thresh = cv2.threshold(gray_image, threshold, 255, cv2.THRESH_BINARY)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5), (-1, -1))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, (-1, -1))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, (-1, -1))
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
if len(cnt) < 5:
continue
area = cv2.contourArea(cnt)
if area < (minRadius**2) * math.pi or area > (maxRadius**2) * math.pi:
continue
arc_length = cv2.arcLength(cnt, True)
radius = arc_length / (2 * math.pi)
if not (minRadius < radius and radius < maxRadius):
continue
ellipse = cv2.fitEllipse(cnt)
ratio = float(ellipse[1][0]) / float(ellipse[1][1])
if ratio > 0.9 and ratio < 1.1:
corner = cv2.approxPolyDP(cnt, 0.02 * arc_length, True)
cornerNum = len(corner)
if cornerNum > 4: # 當(dāng)cornerNum=4時(shí),識(shí)別矩形;而cornerNum>4時(shí),識(shí)別圓
circles.append(ellipse)
return circles
二、使用
import cv2
from detector.circle_detector import CircleDetector
if __name__ == '__main__':
src = 0
cap = cv2.VideoCapture(src)
detector = CircleDetector()
while True:
if not cap.isOpened():
print('相機(jī)未打開')
break
ret, frame = cap.read()
if not ret:
continue
circles = detector.detectCircles(frame, 158, 50, 200)
img = frame.copy()
for circle in circles:
cv2.circle(img, (int(circle[0][0]), int(circle[0][1])), int(20), (0, 255, 0), thickness=5)
cv2.imshow('image', img)
key = cv2.waitKey(int(1000/30)) & 0xFF
if key == ord(' '):
break
三、注意事項(xiàng)
如果遇到無法識(shí)別,或者誤識(shí)別,注意調(diào)整參數(shù)。文章來源:http://www.zghlxwxcb.cn/news/detail-620902.html
- 確保你圖中所繪圓的半徑在[minRadius, maxRadius]之間。
- 建議使用白背景黑圓作為識(shí)別目標(biāo),否之請(qǐng)自行調(diào)整Threshold,直到識(shí)別效果達(dá)到最佳狀態(tài)(可以查看二值化圖片進(jìn)行分析)。
效果圖
文章來源地址http://www.zghlxwxcb.cn/news/detail-620902.html
到了這里,關(guān)于【OpenCV】高精度識(shí)別圓(支持復(fù)雜場(chǎng)景下的圓)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!