การตรวจจับรูปแบบเรขาคณิตในภาพ:
การตรวจจับวงกลมในภาพ (สามารถเข้าไปดาวน์โหลดไฟล์ภาพได้จาก >> คลิกเพื่อดาวน์โหลด)
import cv2
import numpy as np
# Load the image
img = cv2.imread(r'C:\Users\user\Desktop\shape.jpg', cv2.IMREAD_COLOR)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Convert to grayscale
# Apply Gaussian blur to reduce noise
blurred = cv2.GaussianBlur(gray, (9, 9), 2)
# Detect circles using HoughCircles
circles = cv2.HoughCircles(blurred, cv2.HOUGH_GRADIENT, dp=1.2, minDist=30,
param1=50, param2=30, minRadius=120, maxRadius=200)
# Check if any circles are detected
if circles is not None:
circles = np.uint16(np.around(circles)) # Convert to integer values
for (x, y, r) in circles[0, :]:
print(f"Circle detected at: X={x}, Y={y}, Radius={r}") # Print coordinates
cv2.circle(img, (x, y), r, (0, 255, 0), 3) # Draw circle
cv2.putText(img, f"({x},{y})", (x - 30, y - r - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
# Show results
cv2.imshow("Detected Circles", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
การตรวจจับสี่เหลี่ยมในภาพ (สามารถเข้าไปดาวน์โหลดไฟล์ภาพได้จาก >> คลิกเพื่อดาวน์โหลด)
import cv2
import numpy as np
# Load the image
img = cv2.imread(r'C:\Users\user\Desktop\shape.jpg', cv2.IMREAD_COLOR)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Convert to grayscale
# Apply Canny edge detection
edges = cv2.Canny(gray, 50, 150)
# Find contours
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Iterate through contours and filter for rectangles
for contour in contours:
approx = cv2.approxPolyDP(contour, 0.02 * cv2.arcLength(contour, True), True)
if len(approx) == 4 and cv2.isContourConvex(approx): # Ensure it's a rectangle
x, y, w, h = cv2.boundingRect(approx)
print(f"Rectangle detected at: X={x}, Y={y}, Width={w}, Height={h}") # Print coordinates
# Draw rectangle on the image
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 3)
# Optional: Label the coordinates on the image
cv2.putText(img, f"({x},{y})", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
# Show results
cv2.imshow("Detected Rectangles", img)
cv2.imshow("Edges", edges)
cv2.waitKey(0)
cv2.destroyAllWindows()