Abs6187 commited on
Commit
2e6171c
·
verified ·
1 Parent(s): 6715d1b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +7 -23
app.py CHANGED
@@ -23,33 +23,28 @@ model = YOLO("best.pt")
23
  class_names = {0: 'With Helmet', 1: 'Without Helmet', 2: 'License Plate'}
24
 
25
  def crop_license_plates(image, detections):
26
- """Crop license plates from the image based on detections"""
27
  cropped_plates = []
28
 
29
- if isinstance(image, str): # If image is a file path
30
  image = Image.open(image)
31
- elif isinstance(image, np.ndarray): # If image is numpy array
32
  image = Image.fromarray(image)
33
 
34
  for detection in detections:
35
  if detection['Object'] == 'License Plate':
36
- # Parse coordinates from position string
37
  pos = detection['Position'].strip('()')
38
  x1, y1 = map(int, pos.split(', '))
39
 
40
- # Parse dimensions
41
  dims = detection['Dimensions']
42
  width, height = map(int, dims.split('x'))
43
  x2, y2 = x1 + width, y1 + height
44
 
45
- # Add some padding around the license plate
46
  padding = 10
47
  x1 = max(0, x1 - padding)
48
  y1 = max(0, y1 - padding)
49
  x2 = min(image.width, x2 + padding)
50
  y2 = min(image.height, y2 + padding)
51
 
52
- # Crop the license plate
53
  cropped_plate = image.crop((x1, y1, x2, y2))
54
  cropped_plates.append({
55
  'image': cropped_plate,
@@ -60,31 +55,25 @@ def crop_license_plates(image, detections):
60
  return cropped_plates
61
 
62
  def create_download_files(annotated_image, cropped_plates, detections):
63
- """Create downloadable files including annotated image and cropped plates"""
64
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
65
 
66
- # Create a temporary directory for files
67
- os.makedirs("temp_downloads", exist_ok=True)
68
 
69
- # Save annotated image
70
- annotated_path = f"temp_downloads/annotated_image_{timestamp}.jpg"
71
  annotated_image.save(annotated_path)
72
 
73
- # Save cropped license plates
74
  plate_paths = []
75
  for i, plate_data in enumerate(cropped_plates):
76
- plate_path = f"temp_downloads/license_plate_{i+1}_{timestamp}.jpg"
77
  plate_data['image'].save(plate_path)
78
  plate_paths.append(plate_path)
79
 
80
- # Create detection report
81
- report_path = f"temp_downloads/detection_report_{timestamp}.csv"
82
  if detections:
83
  df = pd.DataFrame(detections)
84
  df.to_csv(report_path, index=False)
85
 
86
- # Create zip file with all results
87
- zip_path = f"temp_downloads/detection_results_{timestamp}.zip"
88
  with zipfile.ZipFile(zip_path, 'w') as zipf:
89
  zipf.write(annotated_path, f"annotated_image_{timestamp}.jpg")
90
  for plate_path in plate_paths:
@@ -151,7 +140,6 @@ def yoloV8_func(
151
  cropped_plates = crop_license_plates(image, detections)
152
  license_plate_gallery = [plate_data['image'] for plate_data in cropped_plates]
153
 
154
- # Create download files
155
  if cropped_plates or detections:
156
  try:
157
  download_files, _, _ = create_download_files(annotated_image, cropped_plates, detections)
@@ -168,7 +156,6 @@ def yoloV8_func(
168
  for obj, count in counts.items():
169
  stats_text += f"- {obj}: {count}\n"
170
 
171
- # Add license plate info
172
  if cropped_plates:
173
  stats_text += f"\nLicense Plates Cropped: {len(cropped_plates)}\n"
174
 
@@ -180,16 +167,13 @@ def yoloV8_func(
180
  except:
181
  font = ImageFont.load_default()
182
 
183
- # Add semi-transparent background for text
184
  text_bbox = draw.textbbox((0, 0), stats_text, font=font)
185
  text_width = text_bbox[2] - text_bbox[0]
186
  text_height = text_bbox[3] - text_bbox[1]
187
  draw.rectangle([10, 10, 20 + text_width, 20 + text_height], fill=(0, 0, 0, 128))
188
 
189
- # Add text
190
  draw.text((15, 15), stats_text, font=font, fill=(255, 255, 255))
191
 
192
- # Create a detection table for display
193
  detection_table = pd.DataFrame(detections) if detections else pd.DataFrame(columns=["Object", "Confidence", "Position", "Dimensions"])
194
 
195
  return annotated_image, detection_table, stats_text, license_plate_gallery, download_files
 
23
  class_names = {0: 'With Helmet', 1: 'Without Helmet', 2: 'License Plate'}
24
 
25
  def crop_license_plates(image, detections):
 
26
  cropped_plates = []
27
 
28
+ if isinstance(image, str):
29
  image = Image.open(image)
30
+ elif isinstance(image, np.ndarray):
31
  image = Image.fromarray(image)
32
 
33
  for detection in detections:
34
  if detection['Object'] == 'License Plate':
 
35
  pos = detection['Position'].strip('()')
36
  x1, y1 = map(int, pos.split(', '))
37
 
 
38
  dims = detection['Dimensions']
39
  width, height = map(int, dims.split('x'))
40
  x2, y2 = x1 + width, y1 + height
41
 
 
42
  padding = 10
43
  x1 = max(0, x1 - padding)
44
  y1 = max(0, y1 - padding)
45
  x2 = min(image.width, x2 + padding)
46
  y2 = min(image.height, y2 + padding)
47
 
 
48
  cropped_plate = image.crop((x1, y1, x2, y2))
49
  cropped_plates.append({
50
  'image': cropped_plate,
 
55
  return cropped_plates
56
 
57
  def create_download_files(annotated_image, cropped_plates, detections):
 
58
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
59
 
60
+ os.makedirs("temp", exist_ok=True)
 
61
 
62
+ annotated_path = f"temp/annotated_image_{timestamp}.jpg"
 
63
  annotated_image.save(annotated_path)
64
 
 
65
  plate_paths = []
66
  for i, plate_data in enumerate(cropped_plates):
67
+ plate_path = f"temp/license_plate_{i+1}_{timestamp}.jpg"
68
  plate_data['image'].save(plate_path)
69
  plate_paths.append(plate_path)
70
 
71
+ report_path = f"temp/detection_report_{timestamp}.csv"
 
72
  if detections:
73
  df = pd.DataFrame(detections)
74
  df.to_csv(report_path, index=False)
75
 
76
+ zip_path = f"temp/detection_results_{timestamp}.zip"
 
77
  with zipfile.ZipFile(zip_path, 'w') as zipf:
78
  zipf.write(annotated_path, f"annotated_image_{timestamp}.jpg")
79
  for plate_path in plate_paths:
 
140
  cropped_plates = crop_license_plates(image, detections)
141
  license_plate_gallery = [plate_data['image'] for plate_data in cropped_plates]
142
 
 
143
  if cropped_plates or detections:
144
  try:
145
  download_files, _, _ = create_download_files(annotated_image, cropped_plates, detections)
 
156
  for obj, count in counts.items():
157
  stats_text += f"- {obj}: {count}\n"
158
 
 
159
  if cropped_plates:
160
  stats_text += f"\nLicense Plates Cropped: {len(cropped_plates)}\n"
161
 
 
167
  except:
168
  font = ImageFont.load_default()
169
 
 
170
  text_bbox = draw.textbbox((0, 0), stats_text, font=font)
171
  text_width = text_bbox[2] - text_bbox[0]
172
  text_height = text_bbox[3] - text_bbox[1]
173
  draw.rectangle([10, 10, 20 + text_width, 20 + text_height], fill=(0, 0, 0, 128))
174
 
 
175
  draw.text((15, 15), stats_text, font=font, fill=(255, 255, 255))
176
 
 
177
  detection_table = pd.DataFrame(detections) if detections else pd.DataFrame(columns=["Object", "Confidence", "Position", "Dimensions"])
178
 
179
  return annotated_image, detection_table, stats_text, license_plate_gallery, download_files