# data[].attributes.attachment_link.readable_text
# Hands.py

import cv2
import mediapipe as mp
mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_hands = mp.solutions.hands

# ���������
cap = cv2.VideoCapture(0)
with mp_hands.Hands(
    model_complexity=0,
    min_detection_confidence=0.5,
    min_tracking_confidence=0.5) as hands:
  while cap.isOpened():
    success, image = cap.read()
    if not success:
      print("Ignoring empty camera frame.")
      break

    image.flags.writeable = False
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    results = hands.process(image)

    # ��������� ������������ ������
    image.flags.writeable = True
    image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
    if results.multi_hand_landmarks:
      for hand_landmarks in results.multi_hand_landmarks:
        mp_drawing.draw_landmarks(
            image,
            hand_landmarks,
            mp_hands.HAND_CONNECTIONS,
            mp_drawing_styles.get_default_hand_landmarks_style(),
            mp_drawing_styles.get_default_hand_connections_style())
        
    # ������������
    cv2.imshow('MediaPipe Hands', cv2.flip(image, 1))
    if cv2.waitKey(5) & 0xFF == 27:
      break
cap.release()

# data[].attributes.body
8월 30일(금) 정보관 4층 AI실

2:50 ~ 3:10 등록 및 팀빌딩

3:20 ~ 5:00 mediapipe, face detection, hands 강의

5:00 ~ 5:30 저녁식사

5:30 ~ 7:30 모둠별 기획 및 제작

7:30 ~ 8:30 발표 및 갤러리워크, 시상

# data[].attributes.body
강사: 정보 이미숙

보조강사: 졸업생 김태선, 김철주

# data[].attributes.body
1.기획PPT

목표 및 배경: 프로그램 기획의 목적과 배경 설명

프로그램 개요: 프로그램의 주요 내용 및 특성

프로그램 구현: 순서도 및 프로그램

성과 및 기대 효과: 프로그램 실행 후 예상되는 성과와 기대 효과

2.구현 프로그램

# data[].attributes.body
import cv2

import mediapipe as mp

mp_drawing = mp.solutions.drawing_utils

mp_hands = mp.solutions.hands

drawing = False

points = []

def recognize_gesture(hand_landmarks):

index_tip = hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_TIP]

thumb_tip = hand_landmarks.landmark[mp_hands.HandLandmark.THUMB_TIP]

if index_tip.y < thumb_tip.y:

return "Drawing"

else:

return "Not Drawing"

def main():

global drawing, points

cap = cv2.VideoCapture(0)

if not cap.isOpened():

print("웹캠을 열 수 없습니다.")

return

with mp_hands.Hands(

model_complexity=1,

min_detection_confidence=0.7,

min_tracking_confidence=0.7

) as hands:

while True:

success, image = cap.read()

if not success:

print("빈 카메라 프레임을 무시합니다.")

continue

image = cv2.flip(image, 1)

image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

results = hands.process(image_rgb)

if results.multi_hand_landmarks:

for hand_landmarks in results.multi_hand_landmarks:

gesture = recognize_gesture(hand_landmarks)

index_tip = hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_TIP]

x, y = int(index_tip.x image.shape[1]), int(index_tip.y image.shape[0])

if gesture == "Drawing":

drawing = True

points.append((x, y))

else:

drawing = False

mp_drawing.draw_landmarks(image, hand_landmarks, mp_hands.HAND_CONNECTIONS)

if drawing and len(points) > 1:

for i in range(1, len(points)):

cv2.line(image, points[i - 1], points[i], (0, 255, 0), 5)

cv2.imshow('Hand Gesture Drawing', image)

if cv2.waitKey(1) & 0xFF == 27: # ESC 키를 눌러 종료

break

cap.release()

cv2.destroyAllWindows()

if name == "__main__":

main()

# data[].attributes.attachment_link.title
기업가 정신을 바탕으로한 기술의 혁신

# data[].attributes.headline
신세계를 경험할수 있습니다

# data[].attributes.subject
신세계를 경험할수 있습니다

# data[].attributes.body
카메라를 향해 손가락을 들어주세요

# data[].attributes.attachment_link.readable_text
import cv2
import mediapipe as mp
import webbrowser
import time

mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_hands = mp.solutions.hands

def is_thumb_up(hand_landmarks):
    # ��������� ������ ������������ ������������ ������
    thumb_tip = hand_landmarks.landmark[mp_hands.HandLandmark.THUMB_TIP]
    thumb_ip = hand_landmarks.landmark[mp_hands.HandLandmark.THUMB_IP]
    
    # ������ ��������� ������ y ��������� ������ ��������� ��������� y ������������ ��������� ������
    return thumb_tip.y < thumb_ip.y

cap = cv2.VideoCapture(0)
thumb_triggered = False  # ��������� ������ ������ ��������� ������������ ������
last_trigger_time = 0  # ��������������� URL��� ��� ������

with mp_hands.Hands(
    model_complexity=0,
    min_detection_confidence=0.5,
    min_tracking_confidence=0.5) as hands:
    while cap.isOpened():
        success, image = cap.read()
        if not success:
            print("Ignoring empty camera frame.")
            break

        image.flags.writeable = False
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        results = hands.process(image)

        image.flags.writeable = True
        image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
        if results.multi_hand_landmarks:
            for hand_landmarks in results.multi_hand_landmarks:
                mp_drawing.draw_landmarks(
                    image,
                    hand_landmarks,
                    mp_hands.HAND_CONNECTIONS,
                    mp_drawing_styles.get_default_hand_landmarks_style(),
                    mp_drawing_styles.get_default_hand_connections_style())
                
                if is_thumb_up(hand_landmarks):
                    current_time = time.time()
                    if not thumb_triggered and (current_time - last_trigger_time) >= 3:
                        # ��������� ������ ��������� 3������ ������������ URL��� ������ ������
                        webbrowser.open("https://www.youtube.com/watch?v=9R2beCadrAY")
                        thumb_triggered = True
                        last_trigger_time = current_time
                else:
                    thumb_triggered = False  # ��������� ������ ��������� ������ ��������� ������

        # ������������
        cv2.imshow('MediaPipe Hands', cv2.flip(image, 1))
        if cv2.waitKey(5) & 0xFF == 27:
            break

cap.release()
cv2.destroyAllWindows()

# data[].attributes.body
화이트 보드

손 다 펴면 그려지고 주먹 쥐면 멈춤

enter 화이트보드 초기화

키보드 x 버튼 그리기 멈춤

키보드 s 버튼 화이트보드 저장

# data[].attributes.body
import cv2
import mediapipe as mp
import numpy as np
from pynput.keyboard import Controller

# Initialize Mediapipe Hands and drawing utilities
mp_hands = mp.solutions.hands

# Initialize the keyboard controller
keyboard = Controller()

# Initialize webcam
cap = cv2.VideoCapture(0)

# Define the virtual keyboard layout for 'a' to 'z'
keys = list("abcdefghijklmnopqrstuvwxyz")
key_size = 50  # Size of each key
rows = 3  # Number of rows in the virtual keyboard
keys_per_row = 10  # Number of keys per row

# Calculate key positions
key_positions = []
for i in range(rows):
    row_keys = keys[i * keys_per_row: (i + 1) * keys_per_row]
    for j, key in enumerate(row_keys):
        x = 30 + j * (key_size + 10)
        y = 50 + i * (key_size + 10)
        key_positions.append((key, (x, y)))

# Reverse key positions for display
def reverse_key_positions(positions):
    h, w, _ = image.shape
    return [(key, (w - x - key_size, y)) for key, (x, y) in positions]

# List of fingertip landmarks (only thumb and index finger)
fingertip_landmarks = [
    mp_hands.HandLandmark.THUMB_TIP,      # Thumb
    mp_hands.HandLandmark.INDEX_FINGER_TIP # Index Finger
]

# Initialize Mediapipe Hands solution
with mp_hands.Hands(
    model_complexity=0,
    min_detection_confidence=0.5,
    min_tracking_confidence=0.5) as hands:

    # Dictionary to track touch states and previous touch states
    key_touch_states = {key: False for key, _ in key_positions}
    prev_key_touch_states = {key: False for key, _ in key_positions}

    while cap.isOpened():
        success, image = cap.read()
        if not success:
            print("Ignoring empty camera frame.")
            break

        # Convert the image to RGB
        image.flags.writeable = False
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        results = hands.process(image)

        # Convert back to BGR for rendering
        image.flags.writeable = True
        image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
        h, w, _ = image.shape

        # Create a transparent overlay for the keyboard
        overlay = np.zeros((h, w, 4), dtype=np.uint8)
        alpha = 170  # Transparency level (0-255, 255 is fully opaque)

        # Draw the virtual keyboard on the overlay
        reversed_key_positions = reverse_key_positions(key_positions)
        for key, pos in reversed_key_positions:
            x, y = pos
            color = (255, 255, 255)  # Default color is white
            if key_touch_states[key]:
                color = (0, 255, 0)  # Change color to green if the key is pressed
            cv2.rectangle(overlay, (x, y), (x + key_size, y + key_size), color, -1)
            cv2.putText(overlay, key, (x + 15, y + 45), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2)

        # Add alpha channel to the overlay
        overlay = cv2.merge((overlay[:, :, :3], (overlay[:, :, 3] * alpha / 255).astype(np.uint8)))

        # Blend the overlay with the original image
        image = cv2.addWeighted(image, 1.0, overlay[:, :, :3], alpha / 255.0, 0)

        # Reset key touch states
        for key in key_touch_states.keys():
            key_touch_states[key] = False

        # If hand landmarks are detected
        if results.multi_hand_landmarks:
            for hand_landmarks in results.multi_hand_landmarks:
                # Get coordinates of thumb and index fingertip
                fingertip_coords = {}
                for fingertip in fingertip_landmarks:
                    fingertip_coords[fingertip] = hand_landmarks.landmark[fingertip]

                # Check distance between thumb and index finger
                def distance(pt1, pt2):
                    return np.sqrt((pt1.x - pt2.x)**2 + (pt1.y - pt2.y)**2 + (pt1.z - pt2.z)**2)

                # Define a threshold distance for the fingers to be considered close
                close_threshold = 0.05

                thumb_fingertip = fingertip_landmarks[0]
                index_fingertip = fingertip_landmarks[1]
                dist = distance(fingertip_coords[thumb_fingertip], fingertip_coords[index_fingertip])

                if dist < close_threshold:
                    # Mark the keys under the fingertips as touched
                    for key, pos in key_positions:
                        x, y = pos
                        thumb_pixel = (int(fingertip_coords[thumb_fingertip].x * w), int(fingertip_coords[thumb_fingertip].y * h))
                        index_pixel = (int(fingertip_coords[index_fingertip].x * w), int(fingertip_coords[index_fingertip].y * h))

                        x_flipped = w - x - key_size

                        if (x_flipped <= thumb_pixel[0] <= x_flipped + key_size and y <= thumb_pixel[1] <= y + key_size) or \
                           (x_flipped <= index_pixel[0] <= x_flipped + key_size and y <= index_pixel[1] <= y + key_size):
                            key_touch_states[key] = True

        # Print key press event only if the key state has just been changed to pressed
        for key in key_touch_states.keys():
            if key_touch_states[key] and not prev_key_touch_states[key]:
                # Reverse key position for actual input
                actual_key_pos = {k: pos for k, pos in zip(keys, key_positions)}
                reversed_key_pos = reverse_key_positions(key_positions)
                for rev_key, rev_pos in reversed_key_pos:
                    if key == rev_key:
                        # Simulate key press using pynput
                        keyboard.press(key)
                        keyboard.release(key)
                        print(f"{key}",end='')
                        break

        # Update previous key touch states
        prev_key_touch_states = key_touch_states.copy()

        # Mirror the image and show it
        cv2.imshow('Virtual Keyboard', cv2.flip(image, 1))

        # Exit on 'Esc' key press
        if cv2.waitKey(5) & 0xFF == 27:
            break

# Release the capture device
cap.release()
cv2.destroyAllWindows()

# data[].attributes.attachment_link.title
제목 없는 프레젠테이션

# data[].attributes.body
import cv2

import webbrowser

import random

import time

# 유튜브 링크 리스트

youtube_links = [

"https://www.youtube.com/watch?v=frIRfvU6sKE", # 실제 유튜브 링크로 교체하세요

"https://www.youtube.com/watch?v=Q414VnDOZNk",

"https://www.youtube.com/watch?v=FhA37Sw4j8w",

"https://www.youtube.com/watch?v=JF0YwScEMag",

"https://www.youtube.com/watch?v=VsBdl9tFhFk",

"https://www.youtube.com/watch?v=H5kokc0ULuo",

"https://www.youtube.com/watch?v=hcsxPnlh3VY",

"https://www.youtube.com/watch?v=wLoQeRY70RA",

"https://www.youtube.com/watch?v=peMT6N4rI9Q",

"https://www.youtube.com/watch?v=SaecxMkklx8",

"https://www.youtube.com/watch?v=AFU25b2QZt4",

"https://www.youtube.com/watch?v=4eDgnp4e3cY",

"https://www.youtube.com/watch?v=2PESZCT56a8",

"https://www.youtube.com/watch?v=Dfu0QBqAtgE",

"https://www.youtube.com/watch?v=8O1dAhor_K4",

"https://www.youtube.com/watch?v=sturUvSze60",

"https://www.youtube.com/watch?v=asBo6G8gFs8",

"https://www.youtube.com/watch?v=iwHMI1IynVc",

"https://www.youtube.com/watch?v=YfiokqRQ9j4",

"https://www.youtube.com/watch?v=uecovg3W1HI&t=420s",

"https://www.youtube.com/watch?v=abJ0R97juZY",

"https://www.youtube.com/watch?v=ePcphV22OgU",

"https://www.youtube.com/watch?v=sMW2u5xe-jM",

"https://www.youtube.com/watch?v=u1GPYtXDuHE",

"https://www.youtube.com/watch?v=TH3nUCzioNo",

"https://www.youtube.com/watch?v=armCB-Eik5Y",

"https://www.youtube.com/watch?v=WUS79TrTX_k",

"https://www.youtube.com/watch?v=ODWCUAyiFDg",

"https://www.youtube.com/watch?v=5UMqUfZWOWc",

"https://www.youtube.com/watch?v=aSwxiLTrF9o",

"https://www.youtube.com/watch?v=-GsaVY1Qsds",

"https://www.youtube.com/watch?v=JJ0tUT0c4nY",

"https://www.youtube.com/watch?v=5APC-SCEKM8",

"https://www.youtube.com/watch?v=MhOzBLNoFjc",

"https://www.youtube.com/watch?v=-L65fvDjFoA",

"https://www.youtube.com/watch?v=Oo6wLwtu3r4",

# 추가 링크를 여기에 삽입하세요

]

# 얼굴 인식을 위한 CascadeClassifier 로드

face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

# 웹캠을 열어 비디오 캡처 시작

cap = cv2.VideoCapture(0)

print("얼굴을 인식하면 유튜브 링크를 열도록 설정되었습니다.")

print("웹캠 앞에 서주세요. 종료하려면 'q'를 누르세요.")

while True:

# 웹캠에서 프레임을 읽음

ret, frame = cap.read()

if not ret:

print("웹캠에서 프레임을 읽을 수 없습니다. 웹캠이 연결되어 있는지 확인하세요.")

break

# 프레임을 회색조로 변환

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

# 얼굴 인식

faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))

# 얼굴이 인식되었는지 확인

if len(faces) > 0:

# 인식된 얼굴을 표시

for (x, y, w, h) in faces:

cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)

# 3초 동안 얼굴 표시

cv2.imshow('Face Detection', frame)

print("얼굴이 인식되었습니다. 3초 후에 링크를 열겠습니다...")

cv2.waitKey(3000) # 3초 대기

# 랜덤으로 유튜브 링크 선택

video_url = random.choice(youtube_links)

# 웹 브라우저로 링크 열기

webbrowser.open(video_url)

print(f"링크를 열고 있습니다: {video_url}")

# 프로그램 종료

break

# 프레임을 화면에 표시 (디버깅용)

cv2.imshow('Face Detection', frame)

# 'q'를 누르면 프로그램 종료

if cv2.waitKey(1) & 0xFF == ord('q'):

print("사용자가 종료를 요청했습니다.")

break

# 웹캠과 윈도우 종료

cap.release()

cv2.destroyAllWindows()

# data[].attributes.attachment_link.readable_text
import cv2
import mediapipe as mp
import random
import time

# Initialize MediaPipe Hands and drawing utils
mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_hands = mp.solutions.hands

# Initialize video capture
cap = cv2.VideoCapture(0)

# Game settings
target_radius = 30
score = 0
target_position = (0, 0)
start_time = time.time()
game_duration = 30  # game duration in seconds

def draw_target(image, center):
    cv2.circle(image, center, target_radius, (0, 0, 255), -1)

def random_target_position(width, height):
    x = random.randint(target_radius, width - target_radius)
    y = random.randint(target_radius, height - target_radius)
    return (x, y)

def is_finger_close_to_target(finger_x, finger_y, target_x, target_y, radius):
    return (finger_x - target_x) ** 2 + (finger_y - target_y) ** 2 < radius ** 2

with mp_hands.Hands(
    model_complexity=0,
    min_detection_confidence=0.5,
    min_tracking_confidence=0.5) as hands:
    while cap.isOpened():
        success, image = cap.read()
        if not success:
            print("Ignoring empty camera frame.")
            break

        height, width, _ = image.shape
        image.flags.writeable = False
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        results = hands.process(image)

        # Convert back to BGR for display
        image.flags.writeable = True
        image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

        # Draw target
        draw_target(image, target_position)
        
        if results.multi_hand_landmarks:
            for hand_landmarks in results.multi_hand_landmarks:
                mp_drawing.draw_landmarks(
                    image,
                    hand_landmarks,
                    mp_hands.HAND_CONNECTIONS,
                    mp_drawing_styles.get_default_hand_landmarks_style(),
                    mp_drawing_styles.get_default_hand_connections_style())
                
                # Get hand landmark positions
                for landmark in hand_landmarks.landmark:
                    x = int(landmark.x * width)
                    y = int(landmark.y * height)
                    
                    # Check if any finger is close to the target
                    if is_finger_close_to_target(x, y, target_position[0], target_position[1], target_radius):
                        # Target clicked
                        score += 1
                        print(f"Score: {score}")
                        # Move target to a new random position
                        target_position = random_target_position(width, height)
                        break
        
        # Display score and timer
        elapsed_time = time.time() - start_time
        time_left = max(0, int(game_duration - elapsed_time))
        cv2.putText(image, f"Score: {score}", (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)
        cv2.putText(image, f"Time left: {time_left}s", (10, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)
        
        # Show the image
        cv2.imshow('Hand Tracking Target Game', cv2.flip(image, 1))
        
        # Exit on 'ESC'
        if cv2.waitKey(5) & 0xFF == 27 or elapsed_time >= game_duration:
            break

cap.release()
cv2.destroyAllWindows()


# data[].attributes.attachment_link.title
AI메이커톤 자기 평가(응답)