-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
198 lines (166 loc) · 5.82 KB
/
Copy pathapp.py
File metadata and controls
198 lines (166 loc) · 5.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import os
import RPi.GPIO as GPIO
import time
import threading
from flask import Flask, render_template, Response, request
from flask_socketio import SocketIO
from datetime import datetime
import cv2
import numpy as np
import camera
# Flask 앱 설정
app = Flask(__name__)
socketio = SocketIO(app)
UPLOAD_FOLDER = 'static/images'
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
# GPIO 핀 설정
TRIG = 20
ECHO = 16
LED_PINS = [6, 13, 19]
# GPIO 초기화
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)
for pin in LED_PINS:
GPIO.setup(pin, GPIO.OUT)
# 필터 이미지
filters = {
"cat": cv2.imread("static/filters/cat.png", cv2.IMREAD_UNCHANGED),
"bunny": cv2.imread("static/filters/bunny.png", cv2.IMREAD_UNCHANGED),
"dog": cv2.imread("static/filters/dog.png", cv2.IMREAD_UNCHANGED),
"angel": cv2.imread("static/filters/angel.png", cv2.IMREAD_UNCHANGED),
"devil": cv2.imread("static/filters/devil.png", cv2.IMREAD_UNCHANGED),
}
# 얼굴 탐지기 초기화
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
# 전역 변수
selected_filter = None
countdown_active = False
led_blinking = False
# 초음파 센서 거리 측정
def measure_distance(trig, echo):
time.sleep(0.2)
GPIO.output(trig, GPIO.HIGH)
time.sleep(0.00001)
GPIO.output(trig, GPIO.LOW)
while GPIO.input(echo) == 0:
pulse_start = time.time()
while GPIO.input(echo) == 1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 34300 / 2 # 거리 계산 (cm)
return distance
# LED 깜빡임 함수
def blink_leds():
global led_blinking
led_blinking = True
while led_blinking:
for pin in LED_PINS:
GPIO.output(pin, GPIO.HIGH)
time.sleep(0.5)
for pin in LED_PINS:
GPIO.output(pin, GPIO.LOW)
time.sleep(0.5)
# 카운트다운 및 LED 연동
def countdown_with_led():
global countdown_active, led_blinking
countdown_active = True
threading.Thread(target=blink_leds, daemon=True).start()
for i in range(10, 0, -1):
print(f"카운트다운: {i}초 남음")
socketio.emit('countdown', {'time': i})
time.sleep(1)
countdown_active = False
led_blinking = False
for pin in LED_PINS:
GPIO.output(pin, GPIO.LOW)
take_picture()
# 초음파 센서 감지 스레드
def sensor_monitor():
global countdown_active
while True:
try:
distance = measure_distance(TRIG, ECHO)
if distance < 30: # 30cm 이내에서 카운트다운 시작
if not countdown_active:
threading.Thread(target=countdown_with_led, daemon=True).start()
except Exception as e:
print(f"초음파 센서 오류: {e}")
time.sleep(0.5)
# 사진 촬영 함수
def take_picture():
global selected_filter
frame = camera.take_picture()
if frame is None:
print("사진 촬영 실패: 카메라 문제")
return
if selected_filter and selected_filter in filters:
frame = apply_filter(frame, filters[selected_filter])
filename = f"{UPLOAD_FOLDER}/{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
success = cv2.imwrite(filename, frame)
if success:
print(f"사진 저장 성공: {filename}")
else:
print("사진 저장 실패")
# 필터 적용 함수
def apply_filter(frame, filter_image):
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray_frame, scaleFactor=1.1, minNeighbors=5, minSize=(50, 50))
for (x, y, w, h) in faces:
filter_resized = cv2.resize(filter_image, (w, h))
fw, fh = filter_resized.shape[1], filter_resized.shape[0]
alpha_mask = filter_resized[:, :, 3] / 255.0
fy = y - 30
fy = max(fy, 0)
if fy + fh > frame.shape[0]:
fy = frame.shape[0] - fh
for c in range(3):
frame[fy:fy+fh, x:x+fw, c] = (
alpha_mask * filter_resized[:, :, c] +
(1 - alpha_mask) * frame[fy:fy+fh, x:x+fw, c]
)
return frame
# 실시간 비디오 스트리밍
def gen_frames():
global selected_filter
while True:
frame = camera.take_picture()
if frame is None:
continue
if selected_filter and selected_filter in filters:
frame = apply_filter(frame, filters[selected_filter])
ret, buffer = cv2.imencode('.jpg', frame, [cv2.IMWRITE_JPEG_QUALITY, 70])
if not ret:
continue
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + buffer.tobytes() + b'\r\n')
# Flask 라우트
@app.route('/')
def index():
return render_template('index.html')
@app.route('/video_feed')
def video_feed():
return Response(gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/set_filter', methods=['POST'])
def set_filter():
global selected_filter
data = request.get_json()
selected_filter = data.get('filter')
return "필터 설정 성공", 200
@app.route('/start_countdown')
def start_countdown():
global countdown_active
if not countdown_active:
threading.Thread(target=countdown_with_led, daemon=True).start()
return "카운트다운 시작!"
return "이미 카운트다운 중입니다."
if __name__ == '__main__':
camera.init(width=640, height=480)
try:
threading.Thread(target=sensor_monitor, daemon=True).start()
socketio.run(app, host='0.0.0.0', port=5000)
finally:
camera.final()
GPIO.cleanup()