首頁 > 軟體

Python+OpenCV實現單個圓形孔和針檢測

2022-10-30 14:00:40

如果中間紅色區域是針則可以用下面的程式碼檢測,其閾值和斑點檢測的引數根據影象畫素值做相應修改

檢測的主要思路是先通過找到外面的大圓,再通過圓心定位出一個ROI區域,在ROI區域中檢測中心的檢測物件

import os
import cv2
import numpy as np
import math
 
# 檢測針腳位置
def needelCenter_detect(img):
    params = cv2.SimpleBlobDetector_Params()
    # Setup SimpleBlobDetector parameters.
    # print('params')
    # print(params)
    # print(type(params))
 
    # Filter by Area.
    params.filterByArea = True
    params.minArea = 100
    params.maxArea = 10e3
    params.minDistBetweenBlobs = 50
    # params.filterByColor = True
    params.filterByConvexity = False
    # tweak these as you see fit
    # Filter by Circularity
    params.filterByCircularity = False
    params.minCircularity = 0.2
    # params.blobColor = 0
    # # # Filter by Convexity
    # params.filterByConvexity = True
    # params.minConvexity = 0.87
    # Filter by Inertia
    # params.filterByInertia = True
    # params.filterByInertia = False
    # params.minInertiaRatio = 0.01
 
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
 
    # Detect blobs.
    minThreshValue = 110
    _, gray = cv2.threshold(gray, minThreshValue, 255, cv2.THRESH_BINARY)
    # gray = cv2.resize(gray, dsize=None, fx=2, fy=2, interpolation=cv2.INTER_LINEAR)
    # plt.imshow(gray)
    # cv2.imshow("gray",gray)
 
    # 找到距離原點(0,0)最近和最遠的點
 
    detector = cv2.SimpleBlobDetector_create(params)
    keypoints = detector.detect(gray)
    # print(len(keypoints))
    # print(keypoints[0].pt[0])
    # 如果這兒沒檢測到可能會出錯
    if len(keypoints) == 0:
        print("沒有檢測到針角座標,可能需要調整針角斑點檢測引數")
        return keypoints
 
    else:
        print(len(keypoints))
        im_with_keypoints = cv2.drawKeypoints(gray, keypoints, np.array([]), (255, 0, 0),
                                              cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
 
        # if keypoints is not None:
 
        color_img = cv2.cvtColor(im_with_keypoints, cv2.COLOR_BGR2RGB)
        # 畫出圓的圓心
        cv2.circle(color_img, (int(keypoints[0].pt[0]), int(keypoints[0].pt[1])), 5, (0, 255, 0), -1)
        cv2.imshow("color_img",color_img)
        # cv2.waitKey()
 
        return keypoints
 
 
 
# 檢測聯結器圓形位置
def circle_detect(image):
    # 灰度化
    circle_img = image.copy()
    gray = cv2.cvtColor(circle_img, cv2.COLOR_BGR2GRAY)
    # 輸出影象大小,方便根據影象大小調節minRadius和maxRadius
    # print(image.shape)
    # 進行中值濾波
    img = cv2.medianBlur(gray, 3)
 
    # 針角圓心座標
    out_x = 0
    out_y = 0
 
    # 霍夫變換圓檢測
    circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 10e10, param1=100, param2=30, minRadius=10, maxRadius=100)
    # 如果沒檢測到會報錯
    # 這種判斷方式過於簡單
    if circles is None:
        print("沒有檢測到聯結器外圓")
 
    else:
        for circle in circles[0]:
            # 圓的基本資訊
            # print(circle[2])
            # 座標行列-圓心座標
            out_x = int(circle[0])
            out_y = int(circle[1])
            # 半徑
            r = int(circle[2])
            # 在原圖用指定顏色標記出圓的邊界
            cv2.circle(circle_img, (out_x, out_y), r, (0, 0, 255), 2)
            # # 畫出圓的圓心
            cv2.circle(circle_img, (out_x, out_y), 3, (0, 255, 255), -1)
 
 
        # 記錄外圓座標
        out_xpoint = out_x
        out_ypoint = out_y
 
        # 只框出單個針角的位置區域
        step_center = 30
        step_rect = 60
        out_x -= step_center
        out_y -= step_center
 
        needleRect = image[out_y: out_y + step_rect, out_x: out_x + step_rect]
        # cv2.imshow("needleRect", needleRect)
 
        # 根據檢測到的圓形聯結器中心找針角位置
        centerPoint = needelCenter_detect(needleRect)
 
        if len(centerPoint) == 0:
            print("調整位置")
        else:
                # 將針角的座標原還至原圖
            in_x = int(centerPoint[0].pt[0])
            in_y = int(centerPoint[0].pt[1])
            in_x +=   out_x
            in_y +=   out_y
 
            # 畫出針角的圓心
            cv2.circle(circle_img, (in_x, in_y), 3, (0, 255, 0), -1)
 
            # 計算兩者的距離
            # 假設通過標定其一個畫素代表0.0056mm
            DPI = 0.00568
            dis = math.sqrt(math.pow(out_xpoint - in_x,2) + math.pow(out_ypoint - in_y,2))
            print("兩者相互之間的距離為(mm):", dis*DPI)
 
 
            cv2.imshow("image",circle_img)
            cv2.waitKey(1)
 
 
 
if __name__ == "__main__":
 
    # # 測試0 如果是小圖  需要將檢測程式中的cv2.waitKey(1)修改為cv2.waitKey()不然看到圖片
    # image = cv2.imread("images/CircleLinker/CLinker01.jpg")
    # # cv2.imshow("show",image)
    # # cv2.waitKey()
    # roi = image
    # circle_detect(roi)
 
 
 
    # 測試1 從原圖中換到聯結器位置
    image = cv2.imread("SingleImages/src/single.jpg")
    # cv2.imshow("show",image)
    # cv2.waitKey()
    # 如何準確找到圓形聯結器 ---》用yolo訓練後能準備找到
    roi = image[1800:2300, 1800:2300 ]
    # cv2.imshow("show",roi)
    # cv2.waitKey()
    circle_detect(roi)
 
 
 
    # # 測試2 如果是小圖  需要將檢測程式中的cv2.waitKey(1)修改為cv2.waitKey()不然看到圖片
    # image = cv2.imread("SingleImages/single04.jpg")
    # # cv2.imshow("show",image)
    # # cv2.waitKey()
    # roi = image
    # circle_detect(roi)
 
 
 
    # # 測試3 檢測資料夾下所有圖片
    # path = r"D:BUFFERPycharmZhenJiaoDectSingleImages"
    # for filename in os.listdir(path):  # listdir的引數是資料夾的路徑
    #     filenames = path + '\' + filename
    #     # print(filenames)
    #     img_orig = cv2.imread(filenames, 1)
    #     print(filenames)
    #
    #     if img_orig is None:
    #         print("Warning: No Pictures")
    #     else:
    #         circle_detect(img_orig)
 
 
    # # # 測試4 開啟相機測試
    # # 需要將檢測程式中的cv2.waitKey()修改為cv2.waitKey(1)
    # # 否則看到不視訊實時檢測結果
    # capture = cv2.VideoCapture(0)
    #
    # while (True):
    #     # 獲取一幀
    #     ret, frame = capture.read()
    #     circle_detect(frame)
    #
    #     # cv2.imshow('frame', frame)
    #
    #     if cv2.waitKey(1) == ord('q'):
    #         break

以上就是Python+OpenCV實現單個圓形孔和針檢測的詳細內容,更多關於Python OpenCV圓形孔檢測的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com