Liky-yyy commited on
Commit
b778b87
·
1 Parent(s): a399d14

feat: LPIPS로 점수측정방법 변경

Browse files
Files changed (2) hide show
  1. app.py +63 -12
  2. requirements.txt +3 -0
app.py CHANGED
@@ -28,6 +28,13 @@ except ImportError:
28
  return 100
29
  return 20 * np.log10(255.0 / np.sqrt(mse))
30
  import io
 
 
 
 
 
 
 
31
 
32
  class ImageSimilarityLeaderboard:
33
  def __init__(self, reference_image_path="label2.jpg", data_file="leaderboard.json"):
@@ -45,6 +52,16 @@ class ImageSimilarityLeaderboard:
45
  # 락 초기화 후 데이터 로드
46
  self.leaderboard_data = self.load_leaderboard()
47
  self.last_modified = self.get_file_modified_time()
 
 
 
 
 
 
 
 
 
 
48
 
49
  # macOS 호환성을 위한 경고 억제
50
  import warnings
@@ -124,7 +141,35 @@ class ImageSimilarityLeaderboard:
124
 
125
  def calculate_similarity(self, image1, image2):
126
  try:
127
- # 1) 그레이스케일 변환
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  if image1.ndim == 3:
129
  gray1 = cv2.cvtColor(image1, cv2.COLOR_RGB2GRAY)
130
  else:
@@ -135,7 +180,7 @@ class ImageSimilarityLeaderboard:
135
  else:
136
  gray2 = image2.copy()
137
 
138
- # 2) 각 이미지를 독립적으로 표준 크기로 리사이즈 (512x512)
139
  target_size = (512, 512)
140
 
141
  gray1 = cv2.resize(gray1, target_size, interpolation=cv2.INTER_LINEAR)
@@ -164,26 +209,31 @@ class ImageSimilarityLeaderboard:
164
  hist_corr = cv2.compareHist(hist1, hist2, cv2.HISTCMP_CORREL)
165
  hist_score = (hist_corr + 1) / 2 # -1~1 → 0~1
166
 
167
- # 7) 최종 점수 계산 ( 단순하게)
168
- final_score = (ssim_score * 0.7 + hist_score * 0.3) * 100
 
 
 
 
 
 
 
169
 
170
- # 8) PSNR이 높으면 약간의 보너스
171
  if psnr_score > 0.8:
172
- bonus = min((psnr_score - 0.8) * 25, 5) # 최대 5점 보너스
173
  final_score = min(final_score + bonus, 100)
174
 
175
  return {
176
  'ssim': float(ssim_score),
177
- 'psnr': float(psnr_score * 100), # 백분율로 변환
178
  'histogram': float(hist_score),
179
- 'template': 0.0, # 사용하지 않음
180
- 'edge': 0.0, # 사용하지 않음
181
- 'phash': 0.0, # 사용하지 않음
182
  'final_score': float(final_score)
183
  }
184
  except Exception as e:
185
  print(f"유사도 계산 오류: {e}")
186
- return {'ssim':0.0,'psnr':0.0,'histogram':0.0,'template':0.0,'edge':0.0,'phash':0.0,'final_score':0.0}
187
 
188
  def process_image(self, uploaded_image, username):
189
  """업로드된 이미지를 처리하고 점수를 계산합니다."""
@@ -247,7 +297,8 @@ class ImageSimilarityLeaderboard:
247
  'date': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
248
  'ssim': float(round(similarity_scores['ssim'], 4)),
249
  'psnr': float(round(similarity_scores['psnr'], 2)),
250
- 'histogram': float(round(similarity_scores['histogram'], 4))
 
251
  }
252
 
253
  # 같은 이름의 기존 기록이 있는지 확인하고, 더 높은 점수만 유지
 
28
  return 100
29
  return 20 * np.log10(255.0 / np.sqrt(mse))
30
  import io
31
+ import torch
32
+ import lpips
33
+ import torchvision.transforms as transforms
34
+ import ssl
35
+
36
+ # Fix SSL error for model download (macOS specific)
37
+ ssl._create_default_https_context = ssl._create_unverified_context
38
 
39
  class ImageSimilarityLeaderboard:
40
  def __init__(self, reference_image_path="label2.jpg", data_file="leaderboard.json"):
 
52
  # 락 초기화 후 데이터 로드
53
  self.leaderboard_data = self.load_leaderboard()
54
  self.last_modified = self.get_file_modified_time()
55
+
56
+ # LPIPS 모델 초기화 (한 번만 로드)
57
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
58
+ try:
59
+ self.lpips_model = lpips.LPIPS(net='vgg').to(self.device)
60
+ self.lpips_model.eval() # 평가 모드
61
+ print(f"✅ LPIPS 모델 로드 완료 (Device: {self.device})")
62
+ except Exception as e:
63
+ print(f"⚠️ LPIPS 모델 로드 실패: {e}")
64
+ self.lpips_model = None
65
 
66
  # macOS 호환성을 위한 경고 억제
67
  import warnings
 
141
 
142
  def calculate_similarity(self, image1, image2):
143
  try:
144
+ # 1) LPIPS 계산 (Perceptual Similarity) - 가장 중요
145
+ lpips_score = 0.0
146
+ if self.lpips_model is not None:
147
+ try:
148
+ # LPIPS를 위한 전처리 (-1 ~ 1 사이 값으로 정규화, RGB)
149
+ # 이미지 크기는 224x224 이상 권장, 여기서는 256x256으로 리사이즈
150
+ lpips_size = (256, 256)
151
+
152
+ # numpy -> tensor
153
+ img1_t = cv2.resize(image1, lpips_size).astype(np.float32) / 127.5 - 1.0
154
+ img2_t = cv2.resize(image2, lpips_size).astype(np.float32) / 127.5 - 1.0
155
+
156
+ img1_t = torch.from_numpy(img1_t).permute(2, 0, 1).unsqueeze(0).to(self.device)
157
+ img2_t = torch.from_numpy(img2_t).permute(2, 0, 1).unsqueeze(0).to(self.device)
158
+
159
+ with torch.no_grad():
160
+ d = self.lpips_model(img1_t, img2_t)
161
+ dist = d.item()
162
+
163
+ # LPIPS 거리를 점수로 변환 (0이 동일, 보통 0.5 이상이면 꽤 다름)
164
+ # 거리가 0이면 100점, 0.5면 50점, 1.0이면 0점
165
+ # 조금 더 관대하게: max(0, (1 - dist) * 100)
166
+ lpips_score = max(0, (1 - dist) * 100)
167
+
168
+ except Exception as e:
169
+ print(f"LPIPS 계산 오류: {e}")
170
+ lpips_score = 0.0
171
+
172
+ # 2) 그레이스케일 변환 (기존 로직 유지)
173
  if image1.ndim == 3:
174
  gray1 = cv2.cvtColor(image1, cv2.COLOR_RGB2GRAY)
175
  else:
 
180
  else:
181
  gray2 = image2.copy()
182
 
183
+ # 3) 각 이미지를 독립적으로 표준 크기로 리사이즈 (512x512)
184
  target_size = (512, 512)
185
 
186
  gray1 = cv2.resize(gray1, target_size, interpolation=cv2.INTER_LINEAR)
 
209
  hist_corr = cv2.compareHist(hist1, hist2, cv2.HISTCMP_CORREL)
210
  hist_score = (hist_corr + 1) / 2 # -1~1 → 0~1
211
 
212
+ # 7) 최종 점수 계산 (LPIPS 비중 대폭 강화)
213
+ # LPIPS 모델이 있으면 LPIPS 80%, SSIM 10%, Hist 10%
214
+ # 없으면 기존 방식 (SSIM 70%, Hist 30%)
215
+
216
+ if self.lpips_model is not None:
217
+ final_score = (lpips_score * 0.8) + (ssim_score * 100 * 0.1) + (hist_score * 100 * 0.1)
218
+ else:
219
+ print(f"LPIPS 모델이 없어서 SSIM 70%, Hist 30%로 계산")
220
+ final_score = (ssim_score * 0.7 + hist_score * 0.3) * 100
221
 
222
+ # 8) PSNR이 높으면 약간의 보너스 (최대 5점)
223
  if psnr_score > 0.8:
224
+ bonus = min((psnr_score - 0.8) * 25, 5)
225
  final_score = min(final_score + bonus, 100)
226
 
227
  return {
228
  'ssim': float(ssim_score),
229
+ 'psnr': float(psnr_score * 100),
230
  'histogram': float(hist_score),
231
+ 'lpips': float(lpips_score), # 결과에 포함
 
 
232
  'final_score': float(final_score)
233
  }
234
  except Exception as e:
235
  print(f"유사도 계산 오류: {e}")
236
+ return {'ssim':0.0,'psnr':0.0,'histogram':0.0,'lpips':0.0,'final_score':0.0}
237
 
238
  def process_image(self, uploaded_image, username):
239
  """업로드된 이미지를 처리하고 점수를 계산합니다."""
 
297
  'date': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
298
  'ssim': float(round(similarity_scores['ssim'], 4)),
299
  'psnr': float(round(similarity_scores['psnr'], 2)),
300
+ 'histogram': float(round(similarity_scores['histogram'], 4)),
301
+ 'lpips': float(round(similarity_scores.get('lpips', 0.0), 2))
302
  }
303
 
304
  # 같은 이름의 기존 기록이 있는지 확인하고, 더 높은 점수만 유지
requirements.txt CHANGED
@@ -2,3 +2,6 @@ gradio
2
  opencv-python
3
  numpy
4
  pandas
 
 
 
 
2
  opencv-python
3
  numpy
4
  pandas
5
+ torch
6
+ torchvision
7
+ lpips