តាមដានវត្ថុតាមពណ៌ជាមួយ HSV, inRange និង Contours
សរសេរកម្មវិធីតាមដានបាល់ពណ៌ខៀវ ដែលប្រាប់ថាបាល់នៅខាងឆ្វេង កណ្ដាល ឬស្ដាំ — មូលដ្ឋានសម្រាប់រថយន្តរ៉ូបូតដើរតាមវត្ថុ។
- ប្រើ HSV + cv2.inRange + Morphology ដើម្បីញែកវត្ថុតាមពណ៌
- រកទីតាំង ទំហំ និងចំណុចកណ្ដាល (Centroid) របស់វត្ថុដោយ findContours និង moments
- ចាប់ចលនាដោយ createBackgroundSubtractorMOG2 និងបង្កើនល្បឿន Pipeline (Resize, Grayscale, Frame Skipping)
OpenCV រក្សាទុករូបជា BGR (មិនមែន RGB)។ ការញែកពណ៌ក្នុង BGR ពិបាក ព្រោះពន្លឺប្ដូរបន្តិច តម្លៃ B, G, R ប្ដូរទាំងអស់។ Color Space HSV បំបែក Hue (ប្រភេទពណ៌), Saturation (ភាពដិត) និង Value (ពន្លឺ) ដូច្នេះវត្ថុពណ៌ខៀវនៅតែមាន Hue ប្រហាក់ប្រហែលគ្នា ទោះនៅក្នុងម្លប់ ឬពន្លឺថ្ងៃ។ ក្នុង OpenCV (រូប 8-bit) H មានចន្លោះ 0–179 (មិនមែន 0–360) ចំណែក S និង V មានចន្លោះ 0–255។ ឧ. ពណ៌ខៀវប្រហែល H = 100–130។ ពណ៌ក្រហមស្ថិតនៅចុងទាំងពីរ (0–10 និង 170–179) ដូច្នេះត្រូវបង្កើត Mask ២ ហើយបូកគ្នាដោយ cv2.bitwise_or។
Pipeline ស្តង់ដារ៖ ១) cv2.GaussianBlur កាត់ Noise, ២) cv2.cvtColor(frame, cv2.COLOR_BGR2HSV), ៣) cv2.inRange(hsv, lower, upper) បង្កើត Mask ខ្មៅ-ស (255 = ពណ៌ត្រូវ), ៤) cv2.morphologyEx ជាមួយ MORPH_OPEN លុបចំណុចតូចៗ និង MORPH_CLOSE បិទរន្ធ, ៥) cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) ដែលក្នុង OpenCV 4.x ត្រឡប់តម្លៃ ២ គឺ contours, hierarchy។
ពី Contour ធំបំផុត យើងគណនា៖ ផ្ទៃ cv2.contourArea (ច្រោះចោល Blob តូចជាង ≈800 px ដែលជា Noise), ប្រអប់ cv2.boundingRect និង Centroid ពី Moments cx = frac{M10}{M00}, cy = frac{M01}{M00}។ ការប្រៀបធៀប cx ជាមួយកណ្ដាលរូប (320 សម្រាប់ទទឹង 640) ផ្ដល់សញ្ញា LEFT / CENTRE / RIGHT ដែលអាចបញ្ជូនទៅ gpiozero.Robot ដើម្បីឱ្យរថយន្តបង្វិលតាមបាល់។
Raspberry Pi ដែលរត់តាម SSH គ្មានអេក្រង់ ដូច្នេះ cv2.imshow នឹង Error ឬមិនបង្ហាញ។ ជំនួសវិញ យើងរក្សាទុក debug_frame.jpg និង debug_mask.png រៀងរាល់ 5 វិនាទី ដើម្បីកែតម្លៃ HSV (Tuning)។ តម្លៃ HSV អាស្រ័យលើវត្ថុ និងពន្លឺពិត — ត្រូវវាស់ផ្ទាល់ មិនមែនចម្លងពីអ៊ីនធឺណិតទេ។
- OpenCV ប្រើ BGR; ប្ដូរទៅ HSV ដើម្បីញែកពណ៌បានស្ថិរជាងក្រោមពន្លឺផ្សេងៗ
- Hue ក្នុង OpenCV មានចន្លោះ 0–179; ពណ៌ក្រហមត្រូវការ Mask ២ ចន្លោះ
- OpenCV 4.x: contours, hierarchy = cv2.findContours(...)
- Centroid = (m10/m00, m01/m00) ប្រើសម្រាប់បញ្ជាទិសរ៉ូបូត
"""Track a coloured ball with an HSV mask and report LEFT / CENTRE / RIGHT."""
import time
import cv2
import numpy as np
from picamera2 import Picamera2
FRAME_SIZE = (640, 480)
# OpenCV 8-bit HSV: H 0-179, S 0-255, V 0-255. Tune for your ball and lighting!
LOWER_BLUE = np.array([100, 120, 70], dtype=np.uint8)
UPPER_BLUE = np.array([130, 255, 255], dtype=np.uint8)
MIN_AREA_PX = 800 # ignore blobs smaller than this (noise)
CENTRE_TOLERANCE = 0.15 # +/-15 % of the width counts as centre
DEBUG_EVERY_S = 5.0 # save debug images (headless-friendly)
KERNEL = np.ones((5, 5), np.uint8)
def find_ball(frame_bgr):
"""Return ((cx, cy, area, (x, y, w, h)) or None, mask)."""
blurred = cv2.GaussianBlur(frame_bgr, (7, 7), 0)
hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, LOWER_BLUE, UPPER_BLUE)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, KERNEL) # remove speckles
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, KERNEL) # fill small holes
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if not contours:
return None, mask
largest = max(contours, key=cv2.contourArea)
area = cv2.contourArea(largest)
if area < MIN_AREA_PX:
return None, mask
m = cv2.moments(largest)
cx = int(m["m10"] / m["m00"]) # m00 > 0 because area >= MIN_AREA_PX
cy = int(m["m01"] / m["m00"])
return (cx, cy, int(area), cv2.boundingRect(largest)), mask
def direction(cx, width):
offset = (cx - width / 2) / width
if offset < -CENTRE_TOLERANCE:
return "LEFT"
if offset > CENTRE_TOLERANCE:
return "RIGHT"
return "CENTRE"
def main():
picam2 = Picamera2()
picam2.configure(
picam2.create_video_configuration(main={"size": FRAME_SIZE, "format": "RGB888"})
)
picam2.start()
time.sleep(1)
last_debug = 0.0
last_state = None
try:
while True:
frame = picam2.capture_array()
result, mask = find_ball(frame)
if result:
cx, cy, area, (x, y, w, h) = result
state = direction(cx, FRAME_SIZE[0])
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.circle(frame, (cx, cy), 5, (0, 0, 255), -1)
else:
state = "NO BALL"
if state != last_state: # print only when the state changes
print(time.strftime("%H:%M:%S"), state)
last_state = state
now = time.monotonic()
if now - last_debug >= DEBUG_EVERY_S:
cv2.imwrite("debug_frame.jpg", frame)
cv2.imwrite("debug_mask.png", mask)
last_debug = now
except KeyboardInterrupt:
pass
finally:
picam2.stop()
picam2.close()
if __name__ == "__main__":
main()ការពន្យល់៖ find_ball() អនុវត្ត Pipeline Blur → HSV → inRange → Morphology → findContours ហើយយក Contour ធំបំផុតដើម្បីគណនា Centroid។ កម្មវិធីបោះពុម្ពតែពេលស្ថានភាពប្ដូរ (កាត់បន្ថយ Output) និងរក្សាទុករូប Debug រៀងរាល់ 5 វិនាទី ដើម្បីកែតម្លៃ HSV ពេលរត់តាម SSH។
លំហាត់ OpenCV៖ បំប្លែង BGR → HSV និងបង្កើត Color Mask
បំប្លែងរូបភាព frame ទៅ HSV ដោយ cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) រួចបង្កើត mask ដោយ cv2.inRange(hsv, lower, upper)។
សំណួរវាស់សមត្ថភាព (Knowledge Check)
ឆ្លើយគ្រប់សំណួរ រួចចុច «ពិនិត្យចម្លើយ»។ បើត្រឹមត្រូវ ≥ ៨០% មេរៀននេះនឹងត្រូវបានកត់ត្រាថាបានបញ្ចប់ស្វ័យប្រវត្តិ។
- OpenCV-Python Tutorials (Color Spaces, Thresholding, Contours) docs.opencv.orgមេរៀនផ្លូវការនៃ Changing Colorspaces, Morphological Transformations និង Contours in OpenCV។