Commit 2b1d1579 authored by vaisakh.nair's avatar vaisakh.nair 🎯

new fixes done in directory path

parent 9964ee45
input_path: D:\JK_Data\retraining_data\camera_46_annotated_data.zip
log_level: INFO
log_file: logs/imagecounter.log
plot_file: plots/image_count.png
\ No newline at end of file
import zipfile
import os
import logging
import shutil
import matplotlib.pyplot as plt
import tempfile
import yaml
class ImageCounter:
def __init__(self, input_path):
self.input_path =r'D:\JK_Data\retraining_data\camera_47_annotated_data.zip'
self.temp_dir = None
self.extract_folder = None
self.hour_count = {}
# Setup logging
self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
ch = logging.StreamHandler()
ch.setFormatter(formatter)
self.logger.addHandler(ch)
def extract_zip_file(self):
self.logger.info('Extracting zip file...')
# Create a temporary folder
self.temp_dir = tempfile.mkdtemp()
# Extract the zip file into the temporary folder
with zipfile.ZipFile(self.input_path, 'r') as zip_ref:
# Get the name of the first folder in the zip file
first_folder_name = zip_ref.namelist()[0].split('/')[0]
zip_ref.extractall(self.temp_dir, members=[f for f in zip_ref.namelist() if f.startswith(first_folder_name)])
# Set the extract folder to the path of the folder that contains the image files
self.extract_folder = os.path.join(self.temp_dir, first_folder_name)
def count_images_by_hour(self):
self.logger.info('Counting images by hour...')
for filename in os.listdir(self.extract_folder):
if filename.endswith('.jpg') or filename.endswith('.png'):
if 'camera' in filename:
hour = filename[28:30]
else:
hour = filename[35:37]
if hour in self.hour_count:
self.hour_count[hour] += 1
else:
self.hour_count[hour] = 1
def plot_bar_chart(self):
self.logger.info('Plotting bar chart...')
hours = sorted(list(self.hour_count.keys()))
counts = list(self.hour_count.values())
plt.figure(figsize=(15,8))
plt.bar(hours, counts)
for i, v in enumerate(counts):
plt.text(i, v, str(v), color='black', fontweight='bold', ha='center', va='bottom')
plt.xlabel("Hour's")
plt.xticks(rotation=30)
plt.ylabel('Image Count')
plt.title(f'Hour-wise Image Count --------> Packer -{self.input_path[-20:-19]}')
plt.grid(axis='both',linestyle='--')
#filename = 'image_count.jpg'
#plt.savefig(filename)
#plt.show()
def run(self):
self.logger.info('Running ImageCounter...')
try:
if os.path.isdir(self.input_path):
self.extract_folder = self.input_path
elif os.path.isfile(self.input_path) and self.input_path.endswith('.zip'):
self.extract_zip_file()
else:
self.logger.error('Input path is not a zip file or a folder.')
return
self.logger.info('Extraction of images completed.')
self.count_images_by_hour()
self.logger.info('Images Counted successfully.')
self.plot_bar_chart()
self.logger.info('Bar Plot successfull.')
self.logger.info('ImageCounter completed successfully.')
except Exception as e:
self.logger.error(f'Error running ImageCounter: {e}')
def cleanup(self):
self.logger.info('Cleaning up temporary directory...')
try:
if self.temp_dir:
shutil.rmtree(self.temp_dir)
except Exception as e:
self.logger.error(f'Error while cleaning up temporary directory: {str(e)}')
def save_plot(self, filename='image_count.png'):
#self.logger.info(f'Saving plot as {filename}...')
try:
self.run()
plt.savefig(filename)
self.logger.info(f'Saved plot as {filename}...')
plt.close()
self.cleanup()
return os.path.abspath(filename)
except Exception as e:
self.logger.error(f'Error while saving plot: {str(e)}')
counter = ImageCounter('your input path')
path = counter.save_plot(filename='packer.png')
print('Saved image at:', path)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment