구현 예정
식판 인식(웹캠)

colab에서 yolo11을 통해 학습(yolo11이 edge device에 좋아서…)

학습 완료한 파일
식판 인식 성공 → 식판의 네모와 동그라미가 합쳐서 5개가 인식되면 → 캡쳐하여 로컬에 저장
but, 초점 맞춰 질 시간이 없이 바로 캡쳐가 돼서 사진 화질이 안좋아졌다

import cv2
from ultralytics import YOLO
import time
# 1) YOLO 모델 로드: 커스텀으로 학습한 best.pt 파일 경로를 지정하세요.
model = YOLO('best.pt') # 실제 경로로 수정
# 2) 사진 저장 함수
def auto_capture_tray_with_yolo(conf_thresh=0.5):
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
if not cap.isOpened():
print("카메라 열기 실패")
return
print("YOLO로 식판이 감지되면 자동으로 저장합니다...")
while True:
ret, frame = cap.read()
if not ret:
break
# 3) YOLO 추론 (frame 단일 이미지)
results = model.predict(source=frame, conf=conf_thresh, save=False)
det = results[0]
# 5) 식판 감지 시 저장
if len(det.boxes) >= 5:
filename = f"tray_{int(time.time())}.jpg"
cv2.imwrite(filename, frame)
print(f"[저장] {filename}")
# 6) 화면 표시
cv2.imshow("Camera - Press 'q' to quit", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
auto_capture_tray_with_yolo(conf_thresh=0.5)
위의 문제 해결방법
전체 프레임의 10%마진 크기의 박스를 그리고 그 안에 식판 모양 5개 들어오면 캡쳐 되겠끔 → 식판 모양의 바운딩 박스가 화면에 나타나면 시각적으로 별로 안좋기 때문에 화면에는 나오지 않게 했음
Laplacian 분산 기법을 사용하여 Laplacian 필터로 영상의 2차 미분을 취해 edge성분을 강조하고 그 결과 영상의 분산을 계산하고 분산 값이 크면 edge 정보가 뚜렷하여 선명도가 좋다고 판단하는 방법을 사용

import cv2
from ultralytics import YOLO
import time
import numpy as np
class TrayDetector:
def __init__(self, model_path='best.pt', camera_id=0):
# YOLO 객체 검출 모델 초기화
self.model = YOLO(model_path)
self.conf_thresh = 0.6
# 연속 검출 및 쿨다운 설정
self.detection_count = 0
self.required_detections = 5 # 안정적 감지로 판단할 연속 감지 횟수
self.cooldown_time = 5 # 연속 촬영 방지 시간(초)
# 식판 판별 최소 바운딩 박스 수
self.min_boxes = 5
self.camera_id = camera_id
# 초점 품질 임계값 (Laplacian 분산)
self.focus_threshold = 950.0
def detect_tray(self, frame):
# YOLO 객체 검출
results = self.model.predict(
source=frame,
conf=self.conf_thresh,
save=False,
verbose=False
)
return results[0]
def main():
detector = TrayDetector(model_path='best.pt', camera_id=0)
cap = cv2.VideoCapture(detector.camera_id)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
if not cap.isOpened():
print("카메라 열기 실패")
return
print("식판 감지 중... (종료: 'q')")
last_capture = 0
while True:
ret, frame = cap.read()
if not ret:
break
frame = cv2.flip(frame, -1)
det = detector.detect_tray(frame)
# 바운딩 박스 정보 (x1, y1, x2, y2, score, class)
raw = det.boxes.data.cpu().numpy() if det.boxes is not None else np.empty((0, 6))
boxes = raw[:, :4].astype(int)
current_time = time.time()
# ROI 설정 (전체 프레임의 10% 마진)
h, w = frame.shape[:2]
x1_roi, y1_roi = int(w * 0.1), int(h * 0.1)
x2_roi, y2_roi = int(w * 0.9), int(h * 0.9)
cv2.rectangle(frame, (x1_roi, y1_roi), (x2_roi, y2_roi), (255, 0, 0), 2)
# ROI 내 포함되는 박스 개수 계산
count_in_roi = 0
for (x1, y1, x2, y2) in boxes:
if x1 >= x1_roi and y1 >= y1_roi and x2 <= x2_roi and y2 <= y2_roi:
count_in_roi += 1
# 상태 표시 (ROI 내 박스 개수, 초점 품질)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
focus_metric = cv2.Laplacian(gray, cv2.CV_64F).var()
cv2.putText(frame, f"Focus: {focus_metric:.1f}", (10, 70),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 2)
# 연속 감지 및 ROI 조건
if count_in_roi >= detector.min_boxes:
detector.detection_count += 1
else:
detector.detection_count = 0
# 촬영 조건: 연속 required_detections 회 ROI 내 감지 + 초점 ok + 쿨다운 ok
if (detector.detection_count >= detector.required_detections and
focus_metric >= detector.focus_threshold and
current_time - last_capture > detector.cooldown_time):
filename = f"tray_{int(current_time)}.jpg"
cv2.imwrite(filename, frame)
print(f"[저장] {filename} (Focus: {focus_metric:.1f}, InROI: {count_in_roi})")
last_capture = current_time
detector.detection_count = 0
cv2.imshow("Camera", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
또 문제가 생김
위 문제 해결방법

from flask import Flask, render_template, Response, jsonify
import cv2, os, boto3, logging, queue, time, requests, io
from smartcard.CardMonitoring import CardMonitor,CardObserver
from smartcard.Exceptions import NoCardException
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
cap = cv2.VideoCapture(0, cv2.CAP_V4L2)
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
cap.set(cv2.CAP_PROP_FOURCC, fourcc)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 960)
pk_queue = queue.Queue()
global is_detected, cnt_record
is_detected = False
cnt_record = 0
SERVER_URL=os.environ["SERVER_URL"]
AWS_ACCESS_KEY_ID=os.environ["AWS_ACCESS_KEY_ID"]
AWS_SECRET_ACCESS_KEY=os.environ["AWS_SECRET_ACCESS_KEY"]
AWS_DEFAULT_REGION=os.environ["AWS_DEFAULT_REGION"]
BUCKET=os.environ["BUCKET"]
client = boto3.client('s3',
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
region_name=AWS_DEFAULT_REGION,
)
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(message)s'
)
logging.getLogger('werkzeug').setLevel(logging.WARNING)
def gen_frames():
global cnt_record, is_detected
last_capture = 0
while True:
ref, frame = cap.read()
if not ref:
break
else:
now = time.time()
h, w = frame.shape[:2]
margin_x = int(w * 0.05)
margin_y = int(h * 0.05)
inner_w = w - 2 * margin_x
inner_h = h - 2 * margin_y
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
focus = cv2.Laplacian(gray, cv2.CV_64F).var()
r_top, r_bot = detector.vert_split_ratio
split_y = margin_y + int(inner_h * r_top / (r_top + r_bot))
regions = {}
sum_top = sum(detector.top_col_ratios)
acc = 0
for name, ratio in zip(("side_1","main","side_2"),
detector.top_col_ratios):
x1 = margin_x + int(inner_w * acc / sum_top)
acc += ratio
x2 = margin_x + int(inner_w * acc / sum_top)
regions[name] = (x1, margin_y, x2, split_y)
sum_bot = sum(detector.bot_col_ratios)
acc = 0
for name, ratio in zip(("rice","soup"),
detector.bot_col_ratios):
x1 = margin_x + int(inner_w * acc / sum_bot)
acc += ratio
x2 = margin_x + int(inner_w * acc / sum_bot)
regions[name] = (x1, split_y, x2, margin_y + inner_h)
region_ok = True
for name,(x1,y1,x2,y2) in regions.items():
roi = gray[y1:y2, x1:x2]
var = roi.var()
cv2.rectangle(frame,(x1,y1),(x2,y2),(0,255,0),2)
if var < detector.region_presence_threshold:
region_ok = False
cv2.rectangle(
frame,
(margin_x, margin_y),
(margin_x + inner_w, margin_y + inner_h),
(0, 255, 0),
2
)
cv2.putText(frame,f"Focus:{focus:.0f}",
(10,30), cv2.FONT_HERSHEY_SIMPLEX,
0.8,(0,255,255),2)
# 태깅 후에만 식판 검출 수행
if (focus >= detector.focus_threshold and not pk_queue.empty()):
cnt_record += 1
if cnt_record == 15:
cnt_record = 0
is_detected = True
else:
cnt_record -= 1
if cnt_record < 0:
cnt_record = 0
if (is_detected and
# region_ok and
now - last_capture > detector.cooldown_time and
not pk_queue.empty()):
is_detected = False
text = pk_queue.get()
student_pk, grade, class_num, number, name, gender, status = text.split()
# 서버에 정보 전송
payload = {
'studentPk': int(student_pk),
'grade': int(grade),
'classNum': int(class_num),
'number': int(number),
'studentName': name,
'gender': gender,
'status': status,
's3Url': {}
}
for rname,(x1,y1,x2,y2) in regions.items():
crop = frame[y1:y2, x1:x2]
h, w = crop.shape[:2]
scale = 2.0
new_w, new_h = int(w * scale), int(h * scale)
crop_resized = cv2.resize(
crop,
(new_w, new_h),
interpolation=cv2.INTER_LINEAR
)
fname = f"{name}_{status}_{rname}.jpg"
success, encoded_image = cv2.imencode('.jpg', crop_resized, [cv2.IMWRITE_JPEG_QUALITY, 100])
if not success:
logging.warning(f'인코딩 실패 {rname}')
image_buffer = io.BytesIO(encoded_image.tobytes())
image_buffer.seek(0)
client.upload_fileobj(
Fileobj=image_buffer, Bucket=BUCKET, Key=fname,
ExtraArgs={'ACL':'public-read',
'ContentType':'image/jpeg'}
)
payload['s3Url'][rname] = (
f'https://{BUCKET}.s3.{AWS_DEFAULT_REGION}.amazonaws.com/{fname}'
)
logging.info(f"Uploaded success")
try:
resp = requests.post(SERVER_URL, json=payload, timeout=5)
logging.info(f"POST {resp.status_code}")
except Exception as e:
logging.error(f"POST error: {e}")
last_capture = now
detector.detection_count = 0