'Read latest image file from folder
from pickle import NONE
import cv2
import numpy as np
import easyocr
import glob
import os
import mysql.connector
import datetime, time
def load_image():
ts = 0
found = None
for file_name in glob.glob("C:/Users/*.jpg"):
fts = os.path.getmtime(file_name)
if fts > ts:
ts = fts
found = file_name
return found
def img_text(img):
'''loads an image and recognizes text.'''
reader = easyocr.Reader(['en'])
cropped_image = img[0:280, 0:300]
result = reader.readtext(cropped_image)
high, avg, low = 0, 0, 0
for _, text, prob in result:
if prob < 0.5:
continue
print(f'Detected text: {text} (Probability: {prob:.2f})')
try:
label, t = text.split()
temp = float(t)
except ValueError:
continue # wrong format
if label == 'H':
high = temp
elif label == 'A':
avg = temp
elif label == 'L':
low = temp
print(high, low, avg)
return high, avg, low
def db_entry(temp_max, temp_avg, temp_min, tail, time):
sql = "INSERT INTO monitor_tbl (temp_max, temp_avg, temp_min, filename, created) VALUES (%s, %s, %s, %s, %s)"
val = (f"{temp_max}", f"{temp_avg}", f"{temp_min}", f"{tail}", f"{time}")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "was inserted.")
def read_last_db_file():
mycursor.execute("SELECT filename FROM monitor_tbl ORDER BY CREATED DESC LIMIT 1")
myresult = mycursor.fetchall()
for x in myresult:
return x[0]
exist = False
last_file_detected = read_last_db_file()
while not exist:
if not os.listdir("C:/Users/"):
print("Directory is empty")
time.sleep(0.5)
else:
filename = load_image()
print(filename)
head, tail = os.path.split(filename)
created = datetime.datetime.now()
img= cv2.imread(filename)
cropped_image = img[0:280, 0:300]
print(f"db_last_file: {last_file_detected}, current_detected_image: {filename}")
if last_file_detected == filename:
print("do not add to db")
time.sleep(1)
else:
temp_max, temp_avg, temp_min = img_text(cropped_image)
print(f"high: {temp_max}, average: {temp_avg}, low: {temp_min}, filename: {filename}, time: {created}")
db_entry(temp_max, temp_avg, temp_min, filename, created)
last_file_detected = filename
I am trying to read a image file from a directory and check the database whether the file exist if does wait for new file to show up in folder and do some processing on it and save the result to database. But my code is unable to detect the new file in the directory. Can someone share some insight what am I doing wrong here.
Solution 1:[1]
I tried and simplified the code you provided in the way specific to the question, that's how it works. It will not be too difficult for you to adapt it to your own code. You need to create an exit condition in the while loop, as you already did.
`
previous_file_count = 0;
while True:
files = list(filter(os.path.isfile, glob.glob(path + "*.txt")))
file_count = len(files)
if file_count > previous_file_count:
files.sort(key=lambda x: os.path.getmtime(x))
previous_file_count = file_count
print("last file: ", files[-1])
`
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | point |