Hyunoh430 commited on
Commit
4e38f98
·
verified ·
1 Parent(s): b1a0f86

Upload run.py

Browse files
Files changed (1) hide show
  1. run.py +44 -0
run.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from PIL import Image
3
+ import cv2
4
+ import numpy as np
5
+ import matplotlib.pyplot as plt
6
+ import torchvision.transforms as T
7
+
8
+ def inference_and_save(model, input_image_path, output_image_path, threshold=0.3):
9
+ # 이미지 로드 및 전처리
10
+ img = Image.open(input_image_path).convert("RGB")
11
+ img_tensor = T.ToTensor()(img).unsqueeze(0) # 이미지 텐서로 변환 및 배치 차원 추가
12
+
13
+ # 모델 추론
14
+ with torch.no_grad():
15
+ predictions = model(img_tensor.to(torch.device('cpu'))) # CPU로 모델 실행
16
+
17
+ # 이미지 변환 및 그리기
18
+ img_np = np.array(img) # PIL 이미지를 numpy 배열로 변환
19
+ img_np = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR) # OpenCV 형식으로 변환
20
+
21
+ for i, box in enumerate(predictions[0]['boxes']):
22
+ score = predictions[0]['scores'][i].item()
23
+ if score > threshold: # 신뢰도 점수가 임계값 이상인 경우만 표시
24
+ x1, y1, x2, y2 = map(int, box)
25
+ label = predictions[0]['labels'][i].item()
26
+ cv2.rectangle(img_np, (x1, y1), (x2, y2), (0, 255, 0), 2)
27
+ cv2.putText(img_np, f'Label: {label} Score: {score:.2f}', (x1, y1 - 10),
28
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
29
+
30
+ # 결과 이미지 저장
31
+ cv2.imwrite(output_image_path, img_np)
32
+ print(f'Result saved at {output_image_path}')
33
+
34
+ # 사용 예시
35
+ input_image_path = 'test_video.mp4' # 입력 이미지 경로
36
+ output_image_path = 'r.mp4' # 출력 이미지 저장 경로
37
+
38
+ # 모델 로드
39
+ model_path = '15road_best_model.pt'
40
+ model = torch.load(model_path, map_location=torch.device('cpu'))
41
+ model.eval()
42
+
43
+ # 추론 및 저장
44
+ inference_and_save(model, input_image_path, output_image_path, threshold=0.3)