Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

หาและวาดวงกลมในภาพด้วย OpenCV Python

ใช้ OpenCV cv2.HoughCircles() ตรวจจับวงกลมในภาพ Grayscale ด้วย Hough Transform

Syntax

cv2.HoughCircles(image, method, dp, minDist, param1, param2, minRadius, maxRadius)

Parameters: - image: Grayscale image - method: cv2.HOUGH_GRADIENT (唯一的方法) - dp: Inverse ratio of accumulator resolution to image resolution - minDist: Minimum distance between circle centers - param1: Upper threshold for Canny edge detector - param2: Threshold for center detection (smaller = more circles) - minRadius, maxRadius: Radius constraints

ตัวอย่างโค้ด Python

import cv2
import numpy as np

# โหลดภาพ
image = cv2.imread('circle_ellipse_2.JPG')
output = image.copy()

# แปลง Grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# หาวงกลม
circles = cv2.HoughCircles(
    gray, 
    cv2.HOUGH_GRADIENT, 
    dp=1.3, 
    minDist=100,
    param1=50,
    param2=30,
    minRadius=10,
    maxRadius=100
)

if circles is not None:
    circles = np.round(circles[0, :]).astype("int")
    print("Detected circles:", circles)
    
    for (x, y, r) in circles:
        # วาดวงกลมสีเขียว
        cv2.circle(output, (x, y), r, (0, 255, 0), 2)
        # วาดจุดศูนย์กลาง
        cv2.circle(output, (x, y), 2, (0, 0, 255), 3)

# แสดงผล
cv2.imshow("Detected Circles", output)
cv2.waitKey(0)
cv2.destroyAllWindows()

ผลลัพธ์

Detected circles: [[93 98 84]]

แสดงภาพพร้อมวงกลมสีเขียวและจุดศูนย์กลางสีแดง

Tips การปรับ Parameter

  • dp=1: Accumulator ขนาดเดียวภาพ, dp=2: ครึ่งหนึ่ง
  • param2 น้อย → ตรวจเจอมากขึ้น (แต่ False Positive มากขึ้น)
  • minDist ต้อง > จรัสเส้นผ่านศูนย์กลางเล็กที่สุด
  • Preprocess: Gaussian Blur ช่วยลด Noise