OCR_Dome/ocr01.py

83 lines
2.6 KiB
Python

#!/usr/bin/python
# -*- coding: utf-8 -*-
import pytesseract
from PIL import Image
from pathlib import Path
from datetime import datetime
# import numpy as np
import colorsys
from json_extensions import save_to_json_file, load_from_json_file
save_file = Path('all_measurements.json')
# FOLDER = Path('C:/Mc/Dome/Telecamere/ScreenShots')
# FOLDER = Path('C:/Mc/Dome/Telecamere/ScreenShots2')
FOLDER = Path('C:/Mc/Dome/Telecamere/ScreenShots3')
CROPS = {
'batt_full': (351, 1109, 389, 101),
'name': (175, 143, 750, 109),
# 'batt': (48, 320, 25, 50),
'batt': (56, 345, 9, 2),
'perc': (83, 314, 123, 60),
}
def available_screenshot(base_folder: Path):
for f in base_folder.iterdir():
if f.is_file() and f.suffix == '.jpg' and f.stem.startswith('Screenshot') and f.stem.endswith('0a7d545a89c1640e78c89a2ce00d525b'):
yield f
def main(base_folder: Path, out_folder=Path('crps')):
# for sc in sorted(available_screenshot(base_folder), key=lambda x:x.stem):
found = False
n = 0
if save_file.is_file():
measures = load_from_json_file(save_file)
else:
measures = []
for sc in available_screenshot(base_folder):
n += 1
_, f_date, _ = sc.stem.split('_')
dt = datetime.strptime(f_date[:-3], '%Y-%m-%d-%H-%M-%S')
# obj = {'dt': dt}
obj = {'epoch': dt.timestamp()}
# if f_date != '2025-03-16-07-59-52-21':
# continue
# print(sc.stem)
src_img = Image.open(sc)
for k, crp in CROPS.items():
x0, y0, w, h = crp
x1 = x0 + w
y1 = y0 + h
cropped = src_img.crop((x0, y0, x1, y1))
if k == 'batt':
# new_name = f'{k}_{f_date}.png'
# cropped.save(out_folder / new_name)
tot, grey = 0, 0
for p in cropped.getdata():
tot += 1
r, g, b = p
h, s, v = colorsys.rgb_to_hsv(r / 255, g / 255, b / 255)
if s < 0.1 and v > 0.1:
grey += 1
v = grey / tot
# print(f'{v:.1f}')
obj['charging'] = v > 0.8
# obj['charging'] = is_mostly_white(cropped)
if k != 'batt':
text = pytesseract.image_to_string(cropped)
obj[k] = text
if k == 'batt_full' and len(text) > 3:
found = True
print(f'{f_date}: {obj}')
measures.append(obj)
save_to_json_file('all_measurements.json', measures)
return
if __name__ == '__main__':
main(FOLDER)