-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoverlay.py
executable file
·358 lines (290 loc) · 12.8 KB
/
overlay.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
#!/usr/bin/python
from PIL import Image, ImageDraw, ImageFont
import yaml
import os
import time
import math
import shutil
import sys
import logging
import argparse
import json
from getWeather import get_weather_data
# Add the scripts directory to Python's module path
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), 'scripts'))
def load_camera_state_from_json():
script_dir = os.path.dirname(os.path.realpath(__file__))
camera_state_file = os.path.join(script_dir, 'data', 'camera_state.json')
try:
with open(camera_state_file, "r") as file:
state = json.load(file)
return state["shutter_speed"], state["gain"]
except (FileNotFoundError, KeyError):
return None, None
# Load configuration from yaml file
def load_config(config_path):
with open(config_path, 'r') as config_file:
config = yaml.safe_load(config_file)
return config
# Set up logging
def setup_logging(config):
if config.get('log_overlay'):
log_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'logs')
os.makedirs(log_dir, exist_ok=True)
log_file = os.path.join(log_dir, 'capture-image.log')
logging.basicConfig(filename=log_file, level=logging.INFO, format='%(asctime)s %(levelname)s:%(name)s: %(message)s', datefmt='%m/%d/%Y %H:%M:%S')
return True
else:
return False
# Load the configuration file
config = load_config('/home/pi/raspberrypi-picamera-timelapse/config.yaml')
# Set up logging
logging_enabled = setup_logging(config)
# Create gradient for overlay
def create_gradient(draw, width):
for y in range(120):
r, g, b = 10, 20, 40 + int((64 / 60) * y)
draw.line([(0, y), (width, y)], fill=(r, g, b))
# Draw overlay with camera name
def draw_camera_name(draw, width, config):
font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', 50)
text = f"{config['camera_name']}"
text_x = (width - draw.textbbox(xy=(0, 0), text=text, font=font)[2]) // 2 + 20
text_y = 5
draw.text((text_x, text_y), text, font=font, fill=(255, 255, 255))
# Draw date on overlay
def draw_date(draw, width):
# Create dictionaries of day and month names
day_names = {
'Monday': 'Mandag',
'Tuesday': 'Tirsdag',
'Wednesday': 'Onsdag',
'Thursday': 'Torsdag',
'Friday': 'Fredag',
'Saturday': 'Lørdag',
'Sunday': 'Søndag',
}
month_names = {
'January': 'januar',
'February': 'februar',
'March': 'mars',
'April': 'april',
'May': 'mai',
'June': 'juni',
'July': 'juli',
'August': 'august',
'September': 'september',
'October': 'oktober',
'November': 'november',
'December': 'desember',
}
# Get the date as a string
date_text = time.strftime('%A, %d. %B %Y %H:%M')
# Replace the English day and month names with the Norwegian names
for eng, nor in day_names.items():
date_text = date_text.replace(eng, nor)
for eng, nor in month_names.items():
date_text = date_text.replace(eng, nor)
date_font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', 40)
date_x = (width - draw.textbbox(xy=(0, 0), text=date_text, font=date_font)[2]) // 2 + 20
date_y = 68
draw.text(xy=(date_x, date_y), text=date_text, font=date_font, fill=(255, 255, 255))
# Draw weather icon on overlay
def draw_weather_icon(new_img, weather_data, width):
symbol = weather_data.get('symbol')
# symbol = "lightsleetandthunder"
weather_icon_path = f"/home/pi/raspberrypi-picamera-timelapse/yrimg/{symbol}.png"
if os.path.isfile(weather_icon_path):
weather_icon = Image.open(weather_icon_path).convert('RGBA')
transparent_icon = Image.new('RGBA', weather_icon.size, (255, 255, 255, 0))
transparent_icon.paste(weather_icon, (0, 0), weather_icon)
transparent_icon = transparent_icon.resize((120, 120))
icon_x = 10
icon_y = (100 - transparent_icon.height) // 2
new_img.paste(transparent_icon, (icon_x, icon_y), transparent_icon)
def draw_weather_data(draw, weather_data):
# Define the starting point and spacing for the weather data
temp_x = 180
rain_x = 500
wind_x = 890
wind_icon_x = 490
wind_icon_y = 45
data_y = 26
# Check if weather data is available
if weather_data:
# Extract the necessary weather data
temperature = f"{weather_data['02:00:00:5f:3f:f8']['Temperature']}°C"
wind_speed = f"{weather_data['06:00:00:05:7b:ca']['WindStrength']} m/s"
wind_direction = int(weather_data['06:00:00:05:7b:ca']['WindAngle'])
rain = f"{weather_data['05:00:00:06:5f:30']['Rain']} mm"
# Define the font for the weather data
data_font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', 60)
# Draw the weather data on the image
draw.text((temp_x, data_y), f"{temperature}", font=data_font, fill=(255, 255, 255))
wind_line = f"{wind_speed} fra {wind_direction}°"
draw.text((rain_x, data_y), f"{rain}", font=data_font, fill=(255, 255, 255))
draw.text((wind_x, data_y), wind_line, font=data_font, fill=(255, 255, 255))
# Draw the wind direction arrow
draw_wind_direction_arrow(draw, wind_icon_x, wind_icon_y, 0, wind_line, data_font, wind_direction)
def draw_wind_direction_arrow(draw, data_x, data_y, data_spacing, wind_line, data_font, wind_direction):
# Define the starting point for the arrow
arrow_x = data_x + draw.textbbox((data_x, data_y + data_spacing), wind_line, font=data_font)[2] + 11
arrow_y = data_y + data_spacing + 12
# Define the angle, length, and width of the arrow
angle = math.radians(90 + int(wind_direction))
arrow_length = 30
arrow_width = 12
# Adjust the starting point for the arrow if the wind direction is 180 degrees
if wind_direction == "180":
arrow_y -= arrow_length
# Calculate the points for the arrow
center_x = arrow_x
center_y = arrow_y + arrow_length
x1 = center_x + arrow_length * math.cos(angle)
y1 = center_y + arrow_length * math.sin(angle)
x2 = center_x - arrow_width * math.cos(angle + math.pi / 2)
y2 = center_y - arrow_width * math.sin(angle + math.pi / 2)
x3 = center_x - arrow_width * math.cos(angle - math.pi / 2)
y3 = center_y - arrow_width * math.sin(angle - math.pi / 2)
# Draw the arrow on the image
draw.polygon([(x1, y1 - arrow_length), (x2, y2 - arrow_length), (x3, y3 - arrow_length)], fill=(255, 255, 255))
def draw_pi_info(draw):
from piDataStats import get_pi_data
data = get_pi_data()
# {'CPU Temperature': '40.4', 'Total Memory': '3.53 GB', 'Used Memory': '971.80 MB', 'Memory Usage Percentage': '28.80 %', 'Total Disk Space': '114.21 GB',
# 'Used Disk Space': '7.49 GB', 'Free Disk Space': '102.05 GB', 'Disk Usage Percentage': '6.80 %', 'Load Average': '0.40, 0.24, 0.19', 'Photos Captured Today': 1340,
# 'Total Size of Photos': '377.92 MB'}
temp_x = 2420
temp_y = 16
space_y = 62
data_font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 35)
# Load the shutter_speed and gain
shutter_speed, gain = load_camera_state_from_json()
if shutter_speed is not None and gain is not None:
camera_state_line = f"Shutter speed: {shutter_speed}, Gain: {gain}"
else:
camera_state_line = "Shutter/Gain data not available"
# Check if data is available
if data:
# Extract the necessary data
rpi = f"RaspberryPi 4"
cpu_temperature = f"CPU: {data['CPU Temperature']}°C"
space = f"Lagring: {data['Used Disk Space']} / {data['Total Disk Space']} ({data['Disk Usage Percentage']})"
photos = f"Bilder tatt i dag: {data['Photos Captured Today']} ({data['Total Size of Photos']})"
topStr = f"{rpi}, {cpu_temperature}, {camera_state_line}"
secondStr = f"{space} - {photos}"
# Define the font for the data
# Draw the data on the image
draw.text((temp_x, temp_y),topStr, font=data_font, fill=(220, 220, 255))
draw.text((temp_x, space_y),secondStr, font=data_font, fill=(220, 220, 255))
def crop_and_resize_image(file_path, crop_dimensions, new_size):
"""
Crop and resize the image.
:param file_path: Path to the image file.
:param crop_dimensions: Tuple of (left, top, right, bottom) defining the cropping box.
:param new_size: Tuple of (width, height) defining the new size of the image.
"""
with Image.open(file_path) as img:
# Crop the image
cropped_img = img.crop(crop_dimensions)
# Resize the image
resized_img = cropped_img.resize(new_size)
# Save the modified image back to the original file path
resized_img.save(file_path)
print("Cropping image")
def add_overlay(config, image_path):
print("Add_overlay started")
# Check if cropping is enabled and the necessary dimensions are available in the configuration
if config.get('crop_image', False) and 'main_size' in config and 'crop_size' in config:
# Retrieve the main size and crop size from the configuration
main_size = tuple(config['main_size'])
crop_size = tuple(config['crop_size'])
# Calculate the cropping dimensions (left, top, right, bottom)
left = 0
top = 0
right = crop_size[0]
bottom = crop_size[1]
crop_dimensions = (left, top, right, bottom)
# Crop and resize the image
crop_and_resize_image(image_path, crop_dimensions, main_size)
test_mode = False
# if test_mode == True:
# print("TEST MODE")
# Open the image and get its size
img = Image.open(image_path)
width, height = img.size
exif_data = img.info.get('exif', b'')
# Create a new image with additional height for the overlay
new_height = height + 80
new_img = Image.new('RGB', (width, new_height), (255, 255, 255))
new_img.paste(img, (0, 80))
# Create a draw object for the new image
draw = ImageDraw.Draw(new_img)
# Draw the gradient, overlay, and date on the new image
create_gradient(draw, width)
draw_camera_name(draw, width, config)
draw_date(draw, width)
draw_pi_info(draw)
# Attempt to get the weather data
try:
weather_data = get_weather_data()
if logging_enabled:
logging.info("Weather data retrieved successfully.")
# Attempt to draw the weather icon and data on the new image
try:
draw_weather_icon(new_img, weather_data, width)
draw_weather_data(draw, weather_data)
except Exception as e:
print(f"Failed to load weather data: {e}")
except Exception as e:
print(f"Failed to get weather data: {e}")
weather_data = None
if logging_enabled:
logging.error(f"Failed to get weather data: {e}")
# # Save the new image and copy it to the status file location
if not test_mode:
new_img.save(image_path, exif=exif_data)
else:
new_img.save("/var/www/html/overlay.jpg", exif=exif_data)
# if not test_mode:
print("Overlay added!")
# else:
# shutil.copy2(image_path, "/var/www/html/overlay.jpg")
# print(f"Copying {image_path}, /var/www/html/overlay.jpg")
if __name__ == "__main__":
print("__main__ started")
# Parse command line arguments
parser = argparse.ArgumentParser()
parser.add_argument('--file', help='The file path of the image.')
parser.add_argument('--test', action='store_true', help='Enable test mode.')
args = parser.parse_args()
# Log the image path
if logging_enabled:
logging.info(f"Image path: {args.file}")
# Add the overlay to the image
try:
add_overlay(config, args.file)
if logging_enabled:
logging.info("Overlay added successfully.")
except Exception as e:
print(f"Failed to add overlay: {e}")
if logging_enabled:
logging.error(f"Failed to add overlay: {e}")
# Parse command line arguments
parser = argparse.ArgumentParser()
parser.add_argument('--file', help='The file path of the image.')
parser.add_argument('--test', action='store_true', help='Enable test mode.')
args = parser.parse_args()
# Log the image path
if logging_enabled:
logging.info(f"Image path: {args.file}")
# Attempt to get the weather data
try:
weather_data = get_weather_data()
if logging_enabled:
logging.info("Weather data retrieved successfully.")
except Exception as e:
print(f"Failed to get weather data: {e}")
weather_data = None
if logging_enabled:
logging.error(f"Failed to get weather data: {e}")