Upload 2 files
Browse files- gray.pt +3 -0
- gray_run.py +56 -0
gray.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:54b8b855035f7b6a72d0e3feea3fd536fd57613924e224ab3242262d46f25394
|
| 3 |
+
size 165803162
|
gray_run.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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, class_names=None):
|
| 9 |
+
# 이미지 로드 및 전처리
|
| 10 |
+
img = Image.open(input_image_path).convert("L") # 그레이스케일로 변환
|
| 11 |
+
img = img.resize((128, 128)) # 이미지 크기 조정
|
| 12 |
+
img_tensor = T.ToTensor()(img).unsqueeze(0) # 이미지 텐서로 변환 및 배치 차원 추가
|
| 13 |
+
|
| 14 |
+
# 모델 추론
|
| 15 |
+
with torch.no_grad():
|
| 16 |
+
predictions = model(img_tensor.to(torch.device('cpu'))) # CPU로 모델 실행
|
| 17 |
+
|
| 18 |
+
# 결과 시각화
|
| 19 |
+
fig, ax = plt.subplots(1, figsize=(10, 10))
|
| 20 |
+
img_np = np.array(img)
|
| 21 |
+
ax.imshow(img_np, cmap='gray')
|
| 22 |
+
|
| 23 |
+
for i, (box, score, label) in enumerate(zip(predictions[0]['boxes'], predictions[0]['scores'], predictions[0]['labels'])):
|
| 24 |
+
if score > threshold:
|
| 25 |
+
x1, y1, x2, y2 = map(int, box)
|
| 26 |
+
rect = plt.Rectangle((x1, y1), x2-x1, y2-y1, fill=False, edgecolor='red', linewidth=2)
|
| 27 |
+
ax.add_patch(rect)
|
| 28 |
+
|
| 29 |
+
if class_names:
|
| 30 |
+
class_name = class_names[label.item()]
|
| 31 |
+
else:
|
| 32 |
+
class_name = f"Class {label.item()}"
|
| 33 |
+
|
| 34 |
+
ax.text(x1, y1, f'{class_name}: {score:.2f}', bbox=dict(facecolor='white', alpha=0.5))
|
| 35 |
+
|
| 36 |
+
ax.axis('off')
|
| 37 |
+
plt.tight_layout()
|
| 38 |
+
plt.savefig(output_image_path)
|
| 39 |
+
plt.close()
|
| 40 |
+
|
| 41 |
+
print(f'Result saved at {output_image_path}')
|
| 42 |
+
|
| 43 |
+
# 사용 예시
|
| 44 |
+
input_image_path = '1.png' # 입력 이미지 경로
|
| 45 |
+
output_image_path = 'result_1.png' # 출력 이미지 저장 경로
|
| 46 |
+
|
| 47 |
+
# 모델 로드
|
| 48 |
+
model_path = 'road_best_model.pt'
|
| 49 |
+
model = torch.load(model_path, map_location=torch.device('cpu'))
|
| 50 |
+
model.eval()
|
| 51 |
+
|
| 52 |
+
# 클래스 이름 정의 (예시)
|
| 53 |
+
class_names = {0: 'trafficlight', 1: 'speedlimit', 2: 'crosswalk', 3: 'stop'}
|
| 54 |
+
|
| 55 |
+
# 추론 및 저장
|
| 56 |
+
inference_and_save(model, input_image_path, output_image_path, threshold=0.3, class_names=class_names)
|