import cv2
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
import threading
import time
recording = False
# 웹캠 프레임을 업데이트하는 함수
def update_frame():
ret, frame = cap.read()
if ret:
# OpenCV 이미지를 PIL 이미지로 변환
img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
img = Image.fromarray(img)
imgtk = ImageTk.PhotoImage(image=img)
# 레이블에 이미지 업데이트
video_label.imgtk = imgtk
video_label.configure(image=imgtk)
video_label.after(10, update_frame)
# 사진 찍기 함수
def capture_photo():
ret, frame = cap.read()
if ret:
filepath = filedialog.asksaveasfilename(defaultextension=".jpg", filetypes=[("JPEG files", "*.jpg")])
if filepath:
cv2.imwrite(filepath, frame)
print("사진 저장 완료:", filepath)
# 동영상 녹화 시작 함수
def start_recording():
global recording
if not recording:
recording = True
filepath = filedialog.asksaveasfilename(defaultextension=".mp4", filetypes=[("MP4 files", "*.mp4")])
if filepath:
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(filepath, fourcc, 20.0, (640, 480))
def record():
while recording:
ret, frame = cap.read()
if ret:
out.write(frame)
time.sleep(0.05)
out.release()
print("동영상 저장 완료:", filepath)
threading.Thread(target=record).start()
# 녹화 중지 함수
def stop_recording():
global recording
if recording:
recording = False
print("녹화 중지")
# tkinter 윈도우 설정
root = tk.Tk()
root.title("웹캠 화면")
# 웹캠 캡처 설정
cap = cv2.VideoCapture(0)
# 비디오 레이블 설정
video_label = tk.Label(root)
video_label.pack()
# 사진 찍기 버튼 추가
capture_button = tk.Button(root, text="사진 찍기", command=capture_photo)
capture_button.pack(side=tk.LEFT, padx=10, pady=10)
# 녹화 시작 버튼 추가
start_record_button = tk.Button(root, text="녹화 시작", command=start_recording)
start_record_button.pack(side=tk.LEFT, padx=10, pady=10)
# 녹화 중지 버튼 추가
stop_record_button = tk.Button(root, text="녹화 중지", command=stop_recording)
stop_record_button.pack(side=tk.RIGHT, padx=10, pady=10)
# 프레임 업데이트 시작
update_frame()
# tkinter 윈도우 실행
root.mainloop()
# 프로그램 종료 시 웹캠 해제
cap.release()

웹캠이 있으면 버튼 위에 화면이 뜨게 됨.
아나콘다 프롬포트 창을 관리자 권한으로 열고 모듈 설치하기
pip install deepface
pip install tf-keras
아래 코드 메모장에 저장하기
메모장 관리자 권한으로 실행하기
경로 → C:\Windows\System32

import cv2
import tkinter as tk
from PIL import Image, ImageTk
import threading
from ultralytics import YOLO
from deepface import DeepFace
# YOLO 모델 로드
model = YOLO('yolov8n.pt')
# tkinter 윈도우 설정
root = tk.Tk()
root.title("YOLOv8 실시간 사람 및 나이 예측")
# 웹캠 캡처 설정
cap = cv2.VideoCapture(0)
# 사물 검출 상태를 저장하는 변수
detecting = False
# 나이 예측 함수
def predict_age(face_img):
try:
# DeepFace를 통해 나이 분석
analysis = DeepFace.analyze(face_img, actions=['age'], enforce_detection=False)
age = int(analysis["age"])
return age
except Exception as e:
print("예측 실패:", e)
return None
# 웹캠 프레임을 업데이트하고 사람 및 나이 예측하는 함수
def update_frame():
global detecting
ret, frame = cap.read()
if ret:
if detecting:
# YOLO 모델로 사람 검출
results = model(frame)
for result in results:
boxes = result.boxes.cpu().numpy()
for box in boxes:
if int(box.cls[0]) == 0: # 0은 'person' 클래스 번호
x1, y1, x2, y2 = map(int, box.xyxy[0])
# 얼굴 영역을 잘라서 나이 예측
face_img = frame[y1:y2, x1:x2]
age = predict_age(face_img)
# 사람 텍스트와 나이 정보 표시
label = f"사람, 나이: {age}" if age is not None else "사람"
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(frame, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# OpenCV 이미지를 PIL 이미지로 변환
img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
img = Image.fromarray(img)
imgtk = ImageTk.PhotoImage(image=img)
# 레이블에 이미지 업데이트
video_label.imgtk = imgtk
video_label.configure(image=imgtk)
video_label.after(10, update_frame)
# 사물 검출 시작 및 중지 함수
def toggle_detection():
global detecting
detecting = not detecting
if detecting:
detection_button.config(text="사물 검출 중지")
print("사물 검출 시작")
else:
detection_button.config(text="사물 검출 시작")
print("사물 검출 중지")
# 비디오 레이블 설정
video_label = tk.Label(root)
video_label.pack()
# 사물 검출 버튼 설정
detection_button = tk.Button(root, text="사물 검출 시작", command=toggle_detection)
detection_button.pack(padx=10, pady=10)
# 프레임 업데이트 시작
update_frame()
# tkinter 윈도우 실행
root.mainloop()
# 프로그램 종료 시 웹캠 해제
cap.release()

나이 예측해보기
python b.py

아나콘다 프롬프트 창을 관리자 권한으로 열고 아래의 프로그램 설치하기
pip install streamlit-webrtc opencv-python-headless
아래의 스크립트를 C:\Windows\System32> 에 c.py 라는 이름으로 저장합니다
import av
import cv2
import streamlit as st
from streamlit_webrtc import webrtc_streamer
st.title("Real-Time Webcam Stream with WebRTC")
def video_frame_callback(frame):
img = frame.to_ndarray(format="bgr24")
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
return av.VideoFrame.from_ndarray(img, format="rgb24")
webrtc_streamer(key="example", video_frame_callback=video_frame_callback)

아나콘다 프롬프트 창에서 아래 코드 입력하기
python -m streamlit run c.py

사물검출해보기
import av
import cv2
import streamlit as st
from streamlit_webrtc import webrtc_streamer
from ultralytics import YOLO
# YOLOv8 모델 로드 (사전 학습된 'yolov8n' 모델 사용)
model = YOLO('yolov8n.pt') # 'yolov8n.pt' 대신 적절한 모델 경로를 입력하세요
st.title("Real-Time Object Detection with YOLOv8 and WebRTC")
# 프레임 처리 콜백 함수
def video_frame_callback(frame):
img = frame.to_ndarray(format="bgr24")
# YOLO 모델을 사용하여 객체 감지 수행
results = model(img)
# 결과에서 각 객체의 바운딩 박스를 그립니다
for result in results[0].boxes:
x1, y1, x2, y2 = map(int, result.xyxy[0]) # 바운딩 박스 좌표
label = result.cls[0] # 클래스 라벨 (사람 등)
confidence = result.conf[0] # 신뢰도 점수
# 클래스 이름 얻기
class_name = model.names[int(label)]
# 사람일 경우 또는 특정 조건 추가 가능
if class_name == "person" or confidence > 0.5:
# 바운딩 박스와 라벨 그리기
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(img, f"{class_name} {confidence:.2f}", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# BGR에서 RGB로 변환 (Streamlit에서 이미지를 표시하기 위해)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
return av.VideoFrame.from_ndarray(img, format="rgb24")
# WebRTC 스트리밍 시작
webrtc_streamer(key="example", video_frame_callback=video_frame_callback)

아나콘다 프롬프트 창에서 아래와 같이 입력하여 실행시키기
python -m streamlit run d.py

