반응형
1. Vusual Studio Code 설치
2. Thonny에서 라이브러리 설치
- 설치방법
- Thonny 실행
- "Tools(도구)" → "Manage packages(패키지 관리)" 클릭
- 검색창에 opencv-python 입력 후 설치(Install) 버튼 클릭
- 같은 방식으로 mediapipe 입력 후 설치(Install) 버튼 클릭
- 설치 완료 후, 쉘(Shell)에서 아래 명령어 실행하여 설치 확인
import cv2
import mediapipe as mp
print(cv2.__version__) # OpenCV 버전 확인
print(mp.__version__) # MediaPipe 버전 확인
- 터미널에서 직접 설치할 경우
- Thonny의 Shell에서 아래 명령어를 직접 입력하여 설치할 수도 있습니다.
pip install opencv-python
pip install mediapipe
3. MediaPipe 예제
1) WebCam.py : openCV로 웹캠 영상 출력하기
import cv2
cap = cv2.VideoCapture(0) # 웹캠 열기
while True:
ret, frame = cap.read() # 프레임 읽기
if not ret:
break
cv2.imshow("Webcam", frame) # 영상 출력
if cv2.waitKey(1) & 0xFF == ord('q'): # 'q'를 누르면 종료
break
cap.release()
cv2.destroyAllWindows()
- 프로그램을 실행한 후 'q'를 누르면 종료됩니다.
2) HandTracking.py : Mediapipe로 손 인식
import cv2
import mediapipe as mp
import time
cap = cv2.VideoCapture(0)
mpHands = mp.solutions.hands
hands = mpHands.Hands()
mpDraw = mp.solutions.drawing_utils
pTime = 0
cTime = 0
while True:
success, img = cap.read()
imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
results = hands.process(imgRGB)
# print(results.multi_hand_landmarks)
if results.multi_hand_landmarks:
for handLms in results.multi_hand_landmarks:
for id, lm in enumerate(handLms.landmark):
# print(id, lm)
h, w, c = img.shape
cx, cy = int(lm.x * w), int(lm.y * h)
print(id, cx, cy)
# if id == 4:
cv2.circle(img, (cx, cy), 15, (255, 0, 255), cv2.FILLED)
mpDraw.draw_landmarks(img, handLms, mpHands.HAND_CONNECTIONS)
cTime = time.time()
fps = 1 / (cTime - pTime)
pTime = cTime
cv2.putText(img, str(int(fps)), (10, 70), cv2.FONT_HERSHEY_PLAIN, 3,
(255, 0, 255), 3)
cv2.imshow("Image", img)
# cv2.waitKey(1)
if cv2.waitKey(1) & 0xFF == ord('q'): # 'q'를 누르면 종료
break
cap.release()
cv2.destroyAllWindows()
- 프로그램을 실행한 후 'q'를 누르면 종료됩니다.
2) FingerColor.py : 손가락으로 색상 터치
import cv2
import mediapipe as mp
import numpy as np
# 미디어파이프 손인식 모듈 초기화
mp_hands = mp.solutions.hands
hands = mp_hands.Hands(max_num_hands=1) # 한 손만 인식하도록 설정
mp_draw = mp.solutions.drawing_utils
# 버튼 클래스 정의
class Button:
def __init__(self, pos, text, color):
self.pos = pos # (x, y, width, height)
self.text = text
self.color = color
def draw(self, img):
x, y, w, h = self.pos
cv2.rectangle(img, (x, y), (x + w, y + h), self.color, cv2.FILLED)
cv2.putText(img, self.text, (x + 10, y + h - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
def is_pressed(self, x, y):
bx, by, bw, bh = self.pos
if bx < x < bx + bw and by < y < by + bh:
return True
return False
# 버튼 생성
buttons = [
Button((50, 50, 150, 100), "Red", (0, 0, 255)),
Button((250, 50, 150, 100), "Blue", (255, 0, 0)),
Button((450, 50, 150, 100), "Yellow", (0, 255, 255))
]
# 웹캠 영상 캡처 객체 생성
cap = cv2.VideoCapture(0)
selected_color_text = ""
while True:
success, img = cap.read()
if not success:
break
img = cv2.flip(img, 1) # 좌우 반전
# 이미지 색상 변환 (BGR에서 RGB로)
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# 손 랜드마크 감지
results = hands.process(img_rgb)
# 버튼 그리기
for button in buttons:
button.draw(img)
if results.multi_hand_landmarks:
for hand_lms in results.multi_hand_landmarks:
# 랜드마크 그리기
mp_draw.draw_landmarks(img, hand_lms, mp_hands.HAND_CONNECTIONS)
# 검지 끝부분 좌표 가져오기 (랜드마크 번호 8번)
h, w, c = img.shape
lm = hand_lms.landmark[8]
x, y = int(lm.x * w), int(lm.y * h)
# 검지 끝에 원 그리기
cv2.circle(img, (x, y), 10, (255, 0, 255), cv2.FILLED)
# 버튼 터치 여부 확인
for button in buttons:
if button.is_pressed(x, y):
selected_color_text = button.text
# 선택된 색상 텍스트 출력
if selected_color_text != "":
cv2.putText(img, selected_color_text, (50, 200), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 0), 4)
# 결과 영상 출력
cv2.imshow("Hand Touch Buttons", img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 자원 해제
cap.release()
cv2.destroyAllWindows()
반응형
'피지컬컴퓨팅 > 라즈베리파이 피코' 카테고리의 다른 글
라즈베리파이 피코 - 초음파센서 활용하기 (0) | 2025.05.28 |
---|---|
라즈베리파이 피코 : 디지털 데이터 읽기 쓰기 - 터치센서, 푸시버튼, LED (0) | 2025.05.28 |
라즈베리파이 피코 : 아날로그 데이터 읽기 쓰기 - 습도 센서 , 조이스틱, 서보모터 (0) | 2025.05.28 |
라즈베리파이 피코 시리얼통신, Mediapipe 활용 (0) | 2025.05.28 |
라즈베리파이 피코란? - 마이크로파이썬 Thonny설치 (0) | 2025.05.24 |