Video & Image Processing
Image & Video Capture
import cv2
img = cv2.imread('images.jpeg')
print(img.shape)
img = cv2.resize(img,(860, 620))
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # RGB2HSV, RGB2GRAY
print(img.shape)
cv2.imshow("Window Title", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
🌈 HSV ဆိုတာဘာလဲ? HSV ဆိုတာ: H = Hue (အရောင်အမျိုးအစား) 🔹 Hue က Red, Green, Blue ဆိုတဲ့ အခြေခံအရောင်တွေပါ။ 🔹 Value က 0° မှ 179° အထိ ရှိတတ်တယ် (OpenCV မှာ Hue ကို 0-179 သာသုံးတယ်) S = Saturation (အရောင်အဆာ) 🔹 အရောင်ရောနှောမှု အဆာကောင်းလား၊ မကောင်းလားဆိုတာ။ 🔹 Value က 0 (အရောင်မရှိဘူး, ဖြူဖြူစင်စင်) မှ 255 (အရောင်ပြည့်ဝ) အထိ။ V = Value (အလင်းအမှောင်) 🔹 အလင်းအတောက်ရှိလား မရှိဘူးလားဆိုတာ။ 🔹 0 ဆိုတာ အမှောင်လုံးဝ၊ 255 ဆိုတာ အလင်းအတောက်။
import cv2
video = cv2.VideoCapture('ITE.mp4')
# video = cv2.VideoCapture(0) # ဒါက Camera ကို ဖွင့်တာ။ 0 ဆိုတာက Default Camera ပါ။
while True:
try:
res, frame = video.read()
cv2.imshow("Video", frame)
except:
pass
if cv2.waitKey(1000) & 0xff == ord('q'): # cv2.waitKey(1000) ထဲက 1000 ဟာ milliseconds ပါ။
break
video.release() # <-- release the camera
cv2.destroyAllWindows()
Canny
import cv2
img = cv2.imread('images.jpeg')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
new_img = cv2.Canny(gray_img, 150, 200)
cv2.imshow("Image", new_img)
cv2.waitKey(0)
cv2.destoryAllWindow()
import cv2
video = cv2.VideoCapture(0)
while True:
try:
ret, frame = video.read()
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
frame = cv2.Canny(frame, 150, 200)
cv2.imshow("Video", frame)
except:
pass
k = cv2.waitKey(1) & 0xff # ESC (keycode 27) to exit
if k == 27:
break
video.release()
cv2.destroyAllWindows()
Erode & Dilate
import cv2
import numpy as np
org_img = cv2.imread('basketball.png')
org_img = cv2.cvtColor(org_img, cv2.COLOR_BGR2GRAY)
new_img = cv2.Canny(org_img, 150, 200)
kernel = np.ones((1, 1),np.uint8)
erode = cv2.erode(new_img, kernel, iterations=1)
# dil = cv2.dilate(new_img, kernel, iterations=1)
cv2.imshow("Image", erode)
# cv2.imshow("Image", dil)
cv2.waitKey(0)
cv2.destroyAllWindows()
Numpy
import cv2
import numpy as np
# blank = np.zeros((500, 500), dtype = 'uint8')
blank = np.zeros((500, 500,3), dtype = 'uint8') #BGR
blank[:] = 150, 160, 200
print(blank)
cv2.imshow('Window', blank)
cv2.waitKey(0)
cv2.destroyAllWindows()
[[[150 160 200]
[150 160 200]
[150 160 200]
...
[150 160 200]
[150 160 200]
[150 160 200]]
[[150 160 200]
[150 160 200]
[150 160 200]
...
[150 160 200]
[150 160 200]
[150 160 200]]
[[150 160 200]
[150 160 200]
[150 160 200]
...
[150 160 200]
[150 160 200]
[150 160 200]]
...
...
...
[150 160 200]
[150 160 200]
[150 160 200]]]
Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...
2025-04-27 10:36:58.758 Python[28592:5208744] +[IMKClient subclass]: chose IMKClient_Modern
2025-04-27 10:36:58.758 Python[28592:5208744] +[IMKInputSession subclass]: chose IMKInputSession_Modern
Rectangle, Circle, Lines & Text
import cv2
import numpy as np
blank = np.zeros((500, 500,3), dtype = 'uint8')
blank[:] = 0, 255, 0
# Rectangle 1
blank[200:300, 300:400] = 255, 0, 0
# Rectangle 2
rect = cv2.rectangle(blank, (0, 0), (250, 500), (255, 0, 0), thickness = 2)
# rect = cv2.rectangle(blank, (0, 0), (250, 500), (255, 0, 0), 2)
# rect = cv2.rectangle(blank, (0, 0), (250, 500), (255, 0, 0), thickness = cv2.FILLED)
# rect = cv2.rectangle(blank, (0, 0), (250, 500), (255, 0, 0), cv2.FILLED)
# Circle
cir = cv2.circle(blank, (blank.shape[1]//2, blank.shape[0]//2), 40, (0, 0, 255), thickness = 5)
# Line
lin1 = cv2.line(blank, (0, 0), (blank.shape[1]//2, blank.shape[0]//2), (255, 255, 255), thickness = 5)
lin2 = cv2.line(blank, (250, 230), (250, 450), (255, 255, 255), thickness = 5)
# Text
text = cv2.putText(blank, "Hello, world!", (100, 300), cv2.FONT_HERSHEY_TRIPLEX, 1.0, (255, 255, 255))
text = cv2.putText(blank, "Hello, world!", (100, 300), cv2.FONT_HERSHEY_TRIPLEX, 1.0, (255, 255, 255), thickness = 5)
text = cv2.putText(blank, "Hello, world!", (100, 300), cv2.FONT_HERSHEY_TRIPLEX, 1.0, (255, 255, 255), 5)
cv2.imshow('Window', blank)
cv2.waitKey(0)
cv2.destroyAllWindows()
Colors Detection & Recognition
import cv2
import numpy as np
web = cv2.VideoCapture(0)
while (1):
_, frame = web.read() # 📸 webcam ကနေ frame တစ်ခုဖတ်တယ်
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # 📷 BGR ကို HSV ပြောင်းတယ်
# 🎯 Red color ရဲ့ HSV Range ခန့်မှန်း & mask တစ်ခုလုပ်တယ်
red_L = np.array([135, 85, 115], np.uint8)
red_U = np.array([185, 250, 250], np.uint8)
redM = cv2.inRange(hsv, red_L, red_U)
# 🧼 Mask ကို ပိုကြည့်ရလွယ်အောင် dilation လုပ်တယ်
kernel = np.ones((5, 5), 'uint8') # 5x5 white box kernel
redM = cv2.dilate(redM, kernel)
# 🟥 Original frame မှာ mask ပြန်တပ်ပြီး သေချာပြတယ်
red = cv2.bitwise_and(frame, frame, mask=redM)
# 📐 Contour တွေရှာတယ် (အနီဖြစ်တဲ့ မျက်နှာပြင်တွေ)
cont, hier = cv2.findContours(redM, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for pic, cont in enumerate(cont): # 🔁 contour တစ်ခုချင်းစီစစ်
area = cv2.contourArea(cont) # 📏 Contour ရဲ့ မျက်နှာပြင်ထုထည်
if (area > 300): # 📌 မျက်နှာပြင် 300 px ထက်ကြီးရင်
x, y, w, h = cv2.boundingRect(cont) # 🔲 rectangle box တည်ဆောက်
frame = cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
cv2.putText(frame, "Red Colour", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255))
cv2.imshow("Detect", frame)
if cv2.waitKey(1) & 0xff == ord('q'):
web.release()
cv2.destroyAllWindows()
import cv2
import numpy as np
web = cv2.VideoCapture(0)
while (1):
_, frame = web.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
red_L = np.array([135, 85, 115], np.uint8)
red_U = np.array([185, 250, 250], np.uint8)
redM = cv2.inRange(hsv, red_L, red_U)
green_L = np.array([30, 55, 75], np.uint8)
green_U = np.array([105, 250, 250], np.uint8)
greenM = cv2.inRange(hsv, green_L, green_U)
kernel = np.ones((5, 5), 'uint8')
redM = cv2.dilate(redM, kernel)
greenM = cv2.dilate(greenM, kernel)
red = cv2.bitwise_and(frame, frame, mask=redM)
green = cv2.bitwise_and(frame, frame, mask=greenM)
cont1, hier1 = cv2.findContours(redM, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cont2, hier2 = cv2.findContours(greenM, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for pic, cont1 in enumerate(cont1):
area = cv2.contourArea(cont1)
if (area > 300):
x, y, w, h = cv2.boundingRect(cont1)
frame = cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
cv2.putText(frame, "Red Colour", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255))
for pic, cont2 in enumerate(cont2):
area = cv2.contourArea(cont2)
if (area > 300):
x, y, w, h = cv2.boundingRect(cont2)
frame = cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(frame, "Green Colour", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 0))
cv2.imshow("Detect", frame)
if cv2.waitKey(1) & 0xff == ord('q'):
web.release()
cv2.destroyAllWindows()
break
Face Detection & Recognition
https://github.com/opencv/opencv.git
import cv2
# 🧠 Haar cascade classifier (မျက်နှာ model) ကို load လုပ်တယ်
face_cascade = cv2.CascadeClassifier('opencv-4.x/data/haarcascades/haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
while True:
_, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 🧠 မျက်နှာတွေကို ရှာတယ် (detectMultiScale ဆိုတာ Classifier ကနေ detect လုပ်တာ)
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
# 1.1 → scale factor (မျက်နှာကို အနည်းငယ်ချဲ့ကြည့်မယ်) / 1.1 ~ 1.3 ဆိုတာက အသုံးများတဲ့ range ဖြစ်တယ်။
# 4 → min neighbors (မျက်နှာထင်ရှားစေဖို့ ယှဉ်တွဲ count) / 3 ~ 6 ဆိုတာက သင့်တော်တဲ့ value တွေ။
for (x, y, w, h) in faces: # 🔁 detect ဖြစ်တဲ့ မျက်နှာတစ်ခုချင်းစီ loop
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 4)
cv2.imshow('Image', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
import cv2
import face_recognition
import os
import numpy as np
# လေ့လာပြီးသား မျက်နှာပုံများ သိမ်းထားတဲ့ Folder
known_faces_dir = "known_faces" # မျက်နှာပုံတွေအတွက် Directory
known_encodings = [] # မျက်နှာ feature vector တွေကို သိမ်းမယ်
known_names = [] # မျက်နှာနာမည်တွေကို သိမ်းမယ်
# Directory ထဲက မျက်နှာပုံများကို Load လုပ်
for filename in os.listdir(known_faces_dir):
if filename.endswith(".jpg") or filename.endswith(".png"): # jpg နဲ့ png ဖိုင်တွေကိုသာ ယူ
image_path = os.path.join(known_faces_dir, filename) # File လမ်းကြောင်း ပြုလုပ်
image = face_recognition.load_image_file(image_path) # မျက်နှာပုံဖတ်
encoding = face_recognition.face_encodings(image)[0] # မျက်နှာ Encoding ထုတ်
known_encodings.append(encoding) # Encoding တွေကို စုထား
name = os.path.splitext(filename)[0] # ဖိုင်နာမည်ကနေ နာမည်ထုတ်
known_names.append(name) # နာမည် စုထား
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
# Frame ကို 1/4 ချုံ့ Resize လုပ် (မြန်မြန် detect လို့ရအောင်)
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
rgb_small_frame = cv2.cvtColor(small_frame, cv2.COLOR_BGR2RGB)
# မျက်နှာတွေကို detect လုပ် + encode ထုတ်
face_locations = face_recognition.face_locations(rgb_small_frame)
face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
# မျက်နှာတစ်ပုံချင်းစီအတွက်
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
# လေ့လာပြီးသားမျက်နှာတွေနဲ့ နှိုင်းယှဉ်
matches = face_recognition.compare_faces(known_encodings, face_encoding)
name = "Unknown" # မတွေ့ရင် Unknown
# မျက်နှာနီးစပ်မှုကို တိုင်းပြီး Best match ရွေး
face_distances = face_recognition.face_distance(known_encodings, face_encoding)
best_match_index = np.argmin(face_distances)
if matches[best_match_index]:
name = known_names[best_match_index] # Best Match နဲ့ Name ထုတ်
# Coordinate တွေကို ပြန်ကြီး (Original Frame အရွယ်)
top *= 4
right *= 4
bottom *= 4
left *= 4
# မျက်နှာပုံပေါ်မှာ Box နဲ့ Label ရိုက်ထည့်
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 255, 0), cv2.FILLED)
cv2.putText(frame, name, (left + 6, bottom - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 1)
cv2.imshow("Face Recognition", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
MediaPipe
import cv2
import mediapipe as mp
# MediaPipe မှာ Drawing အတွက် function တွေ ယူမယ်
mp_drawing = mp.solutions.drawing_utils
# MediaPipe မှာ Holistic (Face + Hands + Pose) detect လုပ်မယ်
mp_holistic = mp.solutions.holistic
cap = cv2.VideoCapture(0)
# Holistic model ကိုသုံးပြီး detection လုပ်မယ်
with mp_holistic.Holistic(
min_detection_confidence=0.5, # Detect မှန်မှန်ကန်ကန် လိုအပ်တဲ့ confidence
min_tracking_confidence=0.5 # Track မှန်မှန်ကန်ကန် လိုအပ်တဲ့ confidence
) as holistic:
while cap.isOpened(): # Camera ဖွင့်နေသရွေ့ loop ဆက်မယ်
ret, frame = cap.read() # Frame တစ်ခုဖမ်းမယ်
img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # BGR ကို RGB ပြောင်း (MediaPipe input format)
results = holistic.process(img) # Holistic model နဲ့ process လုပ်မယ်
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) # ပြန် BGR ပြောင်း (OpenCV display format)
# မျက်နှာ landmark တွေကို ရေးမယ်
mp_drawing.draw_landmarks(frame, results.face_landmarks, mp_holistic.FACEMESH_TESSELATION)
# ညာဘက်လက် landmark တွေကို ရေးမယ်
mp_drawing.draw_landmarks(frame, results.right_hand_landmarks, mp_holistic.HAND_CONNECTIONS)
# ဘယ်ဘက်လက် landmark တွေကို ရေးမယ်
mp_drawing.draw_landmarks(frame, results.left_hand_landmarks, mp_holistic.HAND_CONNECTIONS)
# ခန္ဓာကိုယ် (pose) landmark တွေကို ရေးမယ်
mp_drawing.draw_landmarks(frame, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS)
cv2.imshow("Detect", frame)
if cv2.waitKey(10) & 0xff == ord('q'):
cap.release()
cv2.destroyAllWindows()
Game
Finger Counter
# လိုအပ်တဲ့ library တွေကို import လုပ်
import cv2
import mediapipe as mp
# MediaPipe ထဲက Hand tracking ကို initialize လုပ်
mp_hands = mp.solutions.hands
hands = mp_hands.Hands(max_num_hands=1, min_detection_confidence=0.7) # တစ်လက်သာ ဖမ်းမယ်၊ Detect မှန်မှန်အောင် threshold 0.7
mp_draw = mp.solutions.drawing_utils # လက်အမှတ်တွေနဲ့ ဆက်သွယ်မှုကို ရေးဆွဲဖော်ပြဖို့
# လက်မလေးများ (finger tips) ရဲ့ landmark ID တွေ
finger_tips = [8, 12, 16, 20] # လက်ချောင်းထိပ် IDs
thumb_tip = 4 # လက်မ (thumb) ရဲ့ tip ID
# Webcam ဖွင့်
cap = cv2.VideoCapture(0)
# အဓိက Game Loop
while True:
ret, frame = cap.read()
h, w, _ = frame.shape # Frame အရွယ်အစား သိမ်းထား
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # OpenCV က BGR ဆိုတော့ RGB ပြောင်း
result = hands.process(frame_rgb) # MediaPipe ကို frame ကိုထုတ်ပေး
finger_count = 0 # လက်ချောင်းရေ စောင့်ထား
# လက်တွေတွေ့ရရင်
if result.multi_hand_landmarks:
for hand_landmarks in result.multi_hand_landmarks:
lm_list = [] # Landmark တွေကို သိမ်းမယ်
for id, lm in enumerate(hand_landmarks.landmark):
lm_list.append((int(lm.x * w), int(lm.y * h))) # Landmark တွေရဲ့ (x,y) coordinate ပြောင်း
# လက်မ (Thumb) အတွက် Check
if lm_list[thumb_tip][0] > lm_list[thumb_tip - 1][0]: # လက်မတော်တော်ပေါ်ပြီလား စစ်
finger_count += 1
# အခြားလက်ချောင်း ၄ ခု အတွက် Check
for tip in finger_tips:
if lm_list[tip][1] < lm_list[tip - 2][1]: # လက်ချောင်းထိပ်ပိုမိုမြင့်တက်နေမလား စစ်
finger_count += 1
# လက်အမှတ်တွေနဲ့ ဆက်သွယ်မှုတွေနဲ့ လက်ပုံပေါ်မှာ ဆွဲ
mp_draw.draw_landmarks(frame, hand_landmarks, mp_hands.HAND_CONNECTIONS)
# လက်ချောင်းရေ ကို Screen ပေါ်မှာ ပြမယ်
cv2.putText(frame, f'Fingers: {finger_count}', (50, 100),
cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 3)
# ပြသရန် Window ဖွင့်
cv2.imshow("Finger Counter", frame)
# 'q' နှိပ်ရင် Program ပိတ်
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Webcam ပိတ် + Window ပိတ်
cap.release()
cv2.destroyAllWindows()
Hill Climb
# မီဒီယာပိုက် (Mediapipe) ကို import လုပ်တယ်
import mediapipe as mp
# OpenCV ကို import လုပ်တယ်
import cv2
# Keyboard ကို simulate ဖို့ pyautogui ကို import လုပ်တယ်
import pyautogui
# Mediapipe ထဲက အရေးကြီးတဲ့ modules တွေ ထုတ်ယူထားတယ်
mp_drawing = mp.solutions.drawing_utils
mp_holistic = mp.solutions.holistic
mp_pose = mp.solutions.pose
# Camera ကို ဖွင့်တယ်
cap = cv2.VideoCapture(0)
# Camera ရဲ့ width နဲ့ height ကို ပြင်တယ်
cap.set(3, 560) # Width = 560 pixels
cap.set(4, 400) # Height = 400 pixels
# Holistic Model ကို အသုံးပြုပြီး pose detection စတင်တယ်
with mp_holistic.Holistic(min_detection_confidence=0.5, min_tracking_confidence=0.5) as holistic:
while cap.isOpened(): # Camera ပိတ်မသွားသရွေ့ loop ပြန်တယ်
success, img = cap.read() # တစ်ခုချင်းရိုက်ယူတယ်
img = cv2.flip(img, 1) # ညာဘက်ကို ပြောင်းပြန်ပြတယ်
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # OpenCV image ကို RGB format ပြောင်းတယ်
results = holistic.process(img) # Mediapipe နဲ့ process လုပ်တယ်
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) # ပြန်ပြီး OpenCV BGR ပြန်ပြောင်းတယ်
height, width, _ = img.shape # ပုံရဲ့ အရွယ်အစားယူတယ်
try:
# Right hand (သင့်လက်ဝဲကမျက်နှာပြန်လှည့်ပြီးကြည့်ရတဲ့လက်ညာ) Wrist ကို သိမ်းတယ်
right_hand = (int(results.pose_landmarks.landmark[mp_pose.PoseLandmark.LEFT_WRIST].x * width),
int(results.pose_landmarks.landmark[mp_pose.PoseLandmark.LEFT_WRIST].y * height))
# Left hand (သင့်လက်ညာကမျက်နှာပြန်လှည့်ပြီးကြည့်ရတဲ့လက်ဝဲ) Wrist ကို သိမ်းတယ်
left_hand = (results.pose_landmarks.landmark[mp_pose.PoseLandmark.RIGHT_WRIST].x * width,
results.pose_landmarks.landmark[mp_pose.PoseLandmark.RIGHT_WRIST].y * height)
# ပုံရဲ့ အလယ်ပိုင်း (Y axis) ကို ရှာတယ်
y_mid = height // 2
# လက်ကို တွေ့မြင်တာ ရှင်းပြပေးတယ်
cv2.circle(img, right_hand, 10, (0, 255, 0), cv2.FILLED) # လက်ညာကိုစက်ပြထားတယ် (အစိမ်းရောင်)
cv2.line(img, (width // 2, 0), right_hand, (0, 255, 255), 2) # အပေါ်မှ လက်ညာကို မျဉ်းဆွဲတယ် (အဝါအစိမ်းရောင်)
pose = "Gas" # Default pose ကို Gas လို့သတ်မှတ်ထားတယ်
if right_hand[1] < y_mid:
pose = "Acc" # အပေါ်တက်ရင် accelerate လုပ်တယ်
pyautogui.keyDown('right') # ညာဘက် သွားမယ်
print("Up")
pyautogui.keyUp('left') # ဘယ်ဘက်ရပ်မယ်
elif right_hand[1] > y_mid:
pose = "Break" # အောက်ကျရင် brake လုပ်တယ်
pyautogui.keyDown('left') # ဘယ်ဘက်သွားမယ်
print("Down")
pyautogui.keyUp('right') # ညာဘက်ရပ်မယ်
# မျက်နှာပြင်ပေါ်မှာ pose အတိုင်း စာထည့်ပြသတယ်
cv2.putText(img, pose, (20, 8), cv2.FONT_HERSHEY_PLAIN, 2, (255, 255, 0), 2)
# Y axis အလယ်မျဉ်းကို ပုံထဲမှာဆွဲတယ်
cv2.line(img, (0, y_mid), (width, y_mid), (255, 0, 255), 2)
except:
pass # Error တက်ရင် လွှတ်လိုက်တယ်
# Result ကို ပြတယ်
cv2.imshow("Car Game", img)
# q ကိုနှိပ်ရင် Game ပိတ်မယ်
if cv2.waitKey(1) == ord('q'):
break
# Camera ပိတ်တယ်
cap.release()
# Window တွေ ပိတ်တယ်
cv2.destroyAllWindows()
Basketball
import cv2
import numpy as np
import random
import time
from collections import deque
from imutils.video import VideoStream
import imutils
cap = cv2.VideoCapture(0)
# Game အတွက် Setting များ
levels = 3 # ကစားရမယ့် Level အရေအတွက်
points_per_level = 10 # Level တစ်ခုစီမှာထိရမယ့် point အရေအတွက်
touch_radius = 40 # ဘောလုံးနဲ့ပွိုင့်ကို ထိတဲ့ အဝေးအကွာ (radius)
game_duration = 180 # ဂိမ်းကစားချိန် စုစုပေါင်း (seconds)
font = cv2.FONT_HERSHEY_SIMPLEX # အက္ခရာဖောင့်
padding = 100 # ပွိုင့် random မထွက်ရအောင် edge ကနေ ဝေးတာ
# ဘောလုံးရောင်စပ် (HSV Color Space)
orangeLower = (5, 150, 150)
orangeUpper = (15, 255, 255)
# Game State များ
score = 0 # အမှတ်
current_level = 1 # စတင်မှာ Level 1
points = [] # ပွိုင့်စာရင်း
start_time = time.time() # စတင်ချိန်
point_index = 0 # ပွိုင့် Index
pts = deque(maxlen=64) # ဘောလုံးလမ်းကြောင်း Trail History
# Random Point တစ်ခု ဖန်တီးခြင်း
def generate_random_point(frame):
h, w, _ = frame.shape
return (
random.randint(padding, w - padding),
random.randint(padding, h - padding)
)
# Random Point မှာ အနည်းငယ် Animation ပြသခြင်း
def show_animation(frame, target):
x, y = target
for i in range(10):
radius = 30 + i * 5 # Radius တိုးတက်လာ
color = (0, 255, 255) # အရောင် Yellow
thickness = 10 # Border ထူထူ
temp = frame.copy()
cv2.circle(temp, (x, y), radius, color, thickness)
cv2.imshow("Game", temp)
cv2.waitKey(1)
# Ball tracking နဲ့ Game Loop
while True:
ret, frame = cap.read()
if not ret:
break
frame = cv2.flip(frame, 1) # မျက်နှာပြောင်း
frame = cv2.resize(frame, (1920, 1080)) # Frame size မြှင့်
frame = imutils.resize(frame, width=1500) # နောက်ထပ် resize
# Frame ကို နူးညံ့စေပြီး HSV Color Space ကိုပြောင်း
blurred = cv2.GaussianBlur(frame, (11, 11), 0)
hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)
# ဘောလုံးရောင် mask ပြုလုပ်
mask = cv2.inRange(hsv, orangeLower, orangeUpper)
mask = cv2.erode(mask, None, iterations=2)
mask = cv2.dilate(mask, None, iterations=2)
# ဘောလုံးကိုရှာ
cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
ball_center = None
if len(cnts) > 0:
c = max(cnts, key=cv2.contourArea) # အကြီးဆုံး Contour
((x, y), radius) = cv2.minEnclosingCircle(c)
M = cv2.moments(c)
if M["m00"] > 0:
ball_center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
if radius > 10:
# ဘောလုံးကို Draw လုပ်
cv2.circle(frame, (int(x), int(y)), int(radius), (0, 255, 255), 2)
cv2.circle(frame, ball_center, 5, (0, 0, 255), 10)
# ဘောလုံးလမ်းကြောင်း Update လုပ်
pts.appendleft(ball_center)
# Red Trail လမ်းကြောင်းကို တစ်ချောင်းချင်းဆွဲ
for i in range(1, len(pts)):
if pts[i - 1] is None or pts[i] is None:
continue
thickness = int(np.sqrt(64 / float(i + 1)) * 2.5)
cv2.line(frame, pts[i - 1], pts[i], (250, 205, 126), thickness)
# Random Point များ ဖန်တီး
if len(points) < points_per_level:
points.append(generate_random_point(frame))
# လက်ရှိ Target Point ကို ဆွဲ
if point_index < len(points):
target = points[point_index]
cv2.circle(frame, target, 60, (255, 255, 255), 6) # Outer White
cv2.circle(frame, target, 50, (15, 255, 255), -1) # Inner Blue
# ဘောလုံးနဲ့ ပွိုင့် ထိစစ်
if ball_center and point_index < len(points):
px, py = points[point_index]
bx, by = ball_center
dist = np.sqrt((bx - px) ** 2 + (by - py) ** 2)
if dist < touch_radius + 20:
score += 10 # အမှတ်ပေါင်း
show_animation(frame, target) # Animation ပြ
point_index += 1 # နောက်ပွိုင့်ဆက်
if point_index == points_per_level:
current_level += 1 # Level တိုး
point_index = 0
points = []
if current_level > levels:
break
# Game အခြေအနေတွေ ပြသ
elapsed_time = int(time.time() - start_time)
remaining_time = max(0, game_duration - elapsed_time)
cv2.putText(frame, f"Level: {min(current_level, levels)}", (1350, 40), font, 1, (0, 0, 0), 2)
cv2.putText(frame, f"Score: {score}", (10, 40), font, 1, (0, 0, 0), 2)
cv2.putText(frame, f"Time: {remaining_time}s", (650, 40), font, 1, (0, 0, 0), 2)
cv2.imshow("Game", frame)
# Game ပြီးဆုံးပဲဖြစ်ဖြစ် Quit နှိပ်ရင် break
if remaining_time <= 0 or current_level > levels:
break
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# ဂိမ်းအဆုံးအတွင် ပြသရန်
cap.release()
cv2.destroyAllWindows()
# Final Screen ပြသ
final_frame = 255 * np.ones((480, 640, 3), dtype=np.uint8)
cv2.putText(final_frame, "Game Over!", (150, 200), font, 2, (0, 0, 255), 3)
cv2.putText(final_frame, f"Final Score: {score}", (150, 270), font, 1.5, (0, 100, 255), 3)
cv2.putText(final_frame, "Press any key to restart...", (80, 350), font, 1, (128, 128, 128), 2)
cv2.imshow("Game Over", final_frame)
cv2.waitKey(0)
cv2.destroyAllWindows()
Last updated