霍夫梯度:檢測的圓與原始影像具有相同的大小
檢測到的相鄰圓的中心的最小距離(如果引數太小,除了一個真實的圓外,還可能會錯誤地檢測到多個相鄰圓,如果太大,可能會漏掉一些圓,)
在#HOUGH梯度的情況下,它是較高的. 兩個閾值傳遞到Canny邊緣檢測器(較低的一個小兩倍),
在#HOUGH梯度的情況下,它是檢測階段圓心的累加器閾值,它越小,就越可能檢測到假圓;minRadius:最小圓半徑maxRadius:最大圓半徑,如果<=0,則使用最大影像尺寸,如果<0,則回傳沒有找到半徑的中心,
PS:在opencv中經常使用cv2.findContours()函式來查找檢測物體的輪廓

"""
-*- coding: utf-8 -*-
author: Hao Hu
@date 2021/12/3 8:00 AM
"""
import math
import cv2
import numpy as np
import matplotlib.pyplot as plt
def circular_detect():
"""霍夫變換圓檢測"""
import cv2
# 載入并顯示圖片
img = cv2.imread('./circular.png')
# 灰度化
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 輸出影像大小,方便根據影像大小調節minRadius和maxRadius
print(img.shape)
ret, thresh1 = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY)
cv2.imshow('thresh1', thresh1)
canny = cv2.Canny(thresh1, 40, 80)
cv2.imshow('Canny', canny)
canny = cv2.blur(canny, (3, 3))
cv2.imshow('blur', canny)
# 霍夫變換圓檢測
circles = cv2.HoughCircles(canny, cv2.HOUGH_GRADIENT, 1, 100, param1=50, param2=30, minRadius=30, maxRadius=150)
# 輸出回傳值,方便查看型別
print('定義了一個三維陣列(x,y,r)',circles)
# 輸出檢測到圓的個數
print(len(circles[0]))
# 根據檢測到圓的資訊,畫出每一個圓
for circle in circles[0]:
if (circle[2] >= 100):
continue
# 圓的基本資訊
print('半徑為',circle[2])
# 坐標行列
x = int(circle[0])
y = int(circle[1])
# 半徑
r = int(circle[2])
# 在原圖用指定顏色標記出圓的位置
img = cv2.circle(img, (x, y), r, (0, 0, 255), -1)
# 顯示新影像
cv2.imshow('circular_detection', img)
def Ellipse_feature_extraction2():
img = cv2.imread("ellipse.png", 3)
imgray = cv2.Canny(img, 600, 100, 3) # Canny邊緣檢測,引數可更改
ret, thresh = cv2.threshold(imgray, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # contours為輪廓集,可以計算輪廓的長度、面積等
for cnt in contours:
if len(cnt) > 50:
S1 = cv2.contourArea(cnt)
ell = cv2.fitEllipse(cnt)
S2 = math.pi * ell[1][0] * ell[1][1]
if (S1 / S2) > 0.2: # 面積比例,可以更改,根據資料集,,,
img = cv2.ellipse(img, ell, (0, 255, 0), 2)
#print(str(S1) + " " + str(S2) + " " + str(ell[0][0]) + " " + str(ell[0][1]))
print(contours[0][0][0],contours[-1][-1][-1])
# 這是橢圓相隔最遠的點
x = (contours[0][0][0][0] + contours[-1][-1][-1][0])/2
y = (contours[0][0][0][1] + contours[-1][-1][-1][1])/2
print('橢圓圓心',x,y)
r = math.sqrt((x-contours[0][0][0][0])*(x-contours[0][0][0][0])+(y-contours[0][0][0][1])*(y-contours[0][0][0][1]))
print('橢圓半徑',r)
cv2.imshow("0", img)
if __name__ == "__main__":
# line_detect_possible_demo()
# circular_detect()
Ellipse_feature_extraction2()
cv2.waitKey(0)
cv2.destroyAllWindows()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/393934.html
標籤:python
