# ======================================================================
# 11회차 | 07 카메라 기능 - 색 찾기 (날지 않음)
# ----------------------------------------------------------------------
# 카메라 화면에서 정한 색의 물체(색종이 카드)를 찾아 네모를 그리고,
# 가운데 위치(cx, cy)와 크기(area)를 알려 준다.
#
# 색을 찾는 방법 (HSV)
#   BGR 화면을 HSV 로 바꾼다.  H = 색깔(0~179), S = 진하기(0~255), V = 밝기(0~255)
#   "H 가 100~130 이고 S, V 가 충분히 크면 파랑" 처럼 범위로 고른다. (빨강은 H 가 0 근처와 179 근처 둘)
#   고른 부분 중 가장 큰 덩어리를 물체로 본다. 너무 작으면(MIN_AREA) 무시.
#
# 키 ("Tello" 창을 클릭한 상태에서)
#   1 빨강   2 파랑   3 초록   4 노랑      c : 화면 가운데의 HSV 값 출력 (범위 맞출 때)
#   q : 끝
#
# 범위 맞추기 : 카드를 화면 가운데에 대고 c 를 눌러 HSV 를 보고, COLORS 의 범위를 고친다.
#              교실 조명에 따라 많이 달라진다!
# ======================================================================

import cv2
import numpy as np

from tello import start

tello_id = "TELLO-58C5B7"      # 내 드론 이름으로 바꾸기

COLORS = {
    "red":    [((0, 120, 70), (10, 255, 255)), ((170, 120, 70), (179, 255, 255))],
    "blue":   [((100, 120, 70), (130, 255, 255))],
    "green":  [((40, 80, 60), (85, 255, 255))],
    "yellow": [((20, 100, 100), (35, 255, 255))],
}
KEYS = {ord("1"): "red", ord("2"): "blue", ord("3"): "green", ord("4"): "yellow"}
MIN_AREA = 2000


def find_color(frame, name):
    """(cx, cy, area, (x, y, w, h)) 또는 None"""
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    mask = None
    for lo, hi in COLORS[name]:
        m = cv2.inRange(hsv, np.array(lo), np.array(hi))
        mask = m if mask is None else cv2.bitwise_or(mask, m)
    mask = cv2.erode(mask, None, iterations=2)
    mask = cv2.dilate(mask, None, iterations=2)
    contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    if not contours:
        return None
    c = max(contours, key=cv2.contourArea)
    area = cv2.contourArea(c)
    if area < MIN_AREA:
        return None
    x, y, w, h = cv2.boundingRect(c)
    return x + w // 2, y + h // 2, area, (x, y, w, h)


def run():
    if not camera.open():
        print("영상을 받지 못했습니다.")
        return
    color = "blue"
    print("1 빨강 / 2 파랑 / 3 초록 / 4 노랑 / c HSV 보기 / q 끝")
    last_print = 0
    while True:
        frame = camera.read_fresh()
        if frame is None:
            cv2.waitKey(10)
            continue
        view = frame.copy()
        found = find_color(frame, color)
        h, w = frame.shape[:2]
        cv2.drawMarker(view, (w // 2, h // 2), (255, 255, 255), cv2.MARKER_CROSS, 30, 2)
        if found:
            cx, cy, area, (x, y, bw, bh) = found
            cv2.rectangle(view, (x, y), (x + bw, y + bh), (0, 255, 0), 3)
            cv2.circle(view, (cx, cy), 6, (0, 0, 255), -1)
            if time.time() - last_print > 0.5:
                print(f"{color}: 가운데 ({cx}, {cy})  크기 {area:.0f}")
                last_print = time.time()
        cv2.putText(view, f"color: {color}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 255), 2)
        cv2.imshow("Tello", view)

        key = cv2.waitKey(1) & 0xFF
        if key == ord("q"):
            break
        if key in KEYS:
            color = KEYS[key]
            print("찾는 색 :", color)
        if key == ord("c"):
            hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
            print("가운데 HSV :", hsv[h // 2, w // 2])
    cv2.destroyAllWindows()


start(tello_id, run)
