Source code for models.model_save_image

"""
This model_save_image module is responsible for managing the saving and handling of images in the MoilApp.
"""
import datetime
import os

import cv2
import yaml


[docs] class ModelSave: """ Class responsible for saving images and managing saved image data. Attributes: _model (object): The main model instance of the application. _pos_video_image_saved (list): A list to store the positions of frames saved from videos. _load_saved_image (bool): A flag indicating whether a saved image is being loaded. Methods: save_image_file(): Save an image file to the specified directory and add metadata to the configuration view. add_position_video_on_saved_image(): Adds the current position of the video to the list of saved positions. reopen_saved_image(): Reopens a saved image file in the main application. clear_saved_image(): Clears the saved image data from the configuration view and updates the configuration file. """ def __init__(self, model): self._model = model self._pos_video_image_saved = [] self._load_saved_image = False @property def pos_video_image_saved(self): """ Gets the position of the saved video image. Returns: The position of the saved video image. """ try: return self._pos_video_image_saved except Exception as e: self._model.activity_logger.error(f"ModelSave.pos_video_image_saved(): Error: {str(e)}") @pos_video_image_saved.setter def pos_video_image_saved(self, value): """ Sets the position of the saved video image. Args: value: The new position to set for the saved video image. """ try: self._pos_video_image_saved = value except Exception as e: self._model.activity_logger.error(f"ModelSave.pos_video_image_saved(): Error: {str(e)}") @property def load_saved_image(self): """ Gets the status of whether a saved image is loaded. Returns: The status indicating if a saved image is loaded. """ try: return self._load_saved_image except Exception as e: self._model.activity_logger.error(f"ModelSave.load_saved_image(): Error: {str(e)}") @load_saved_image.setter def load_saved_image(self, value): """ Sets the status of whether a saved image is loaded. Args: value: The new status to set for loading a saved image. """ try: self._load_saved_image = value except Exception as e: self._model.activity_logger.error(f"ModelSave.load_saved_image(): Error: {str(e)}")
[docs] def save_image_file(self, image, dst_directory, type_camera=None): """ Save an image file to the specified directory and add metadata to the configuration view. Args: image: A NumPy array containing the image data to be saved. dst_directory: A string representing the destination directory to save the image file. type_camera: An optional string representing the type of camera used to capture the image. Returns: A string representing the timestamp in the format "mmdd_HHMMSS" used in the saved image file name. Raises: None """ try: if self._model.debug_mode: self._model.activity_logger.info("ModelSave: save_image_file(), " "Save image file in directory") ss = datetime.datetime.now().strftime("%m%d_%H%M%S") name = dst_directory + str(ss) + ".png" if not os.path.isdir(dst_directory): os.makedirs(os.path.dirname(dst_directory)) cv2.imwrite(name, image) self._model.main_config["Image_saved"][name] = {} self._model.main_config["Image_saved"][name]["parent_path"] = self._model.main_config["Media_path"] # config["Image_saved"][name]["is_video"] = self.model.video self._model.main_config["Image_saved"][name]["state_view"] = self._model.mode_view if self._model.video_config.fps_video != 0.0: self._model.main_config["Image_saved"][name]["pos_frame"] = self._model.video_config.pos_frame_video self._model.saved_image_list = list(self._model.main_config["Image_saved"].keys()) # with open(self.model.config_file, "w") as outfile: # yaml.dump(config, outfile, default_flow_style=False) if type_camera is not None: self._model.write_camera_type(name, type_camera) except Exception as e: self._model.activity_logger.error(f"ModelSave.load_saved_image(): Error: {str(e)}")
[docs] def add_position_video_on_saved_image(self): """ Adds the current position of the video to the list of positions. If there is an active video, this method appends the current position of the video to the list of positions stored in the `pos_video_image_saved` attribute. This list can be used later to create a map of where images were saved in the video. """ try: if self._model.debug_mode: self._model.activity_logger.info("ModelSave: add_position_video_on_saved_image(), " "Add current position frame image on the video ") if self._model.video_config.fps_video != 0.0: self.pos_video_image_saved.append(self._model.video_config.pos_frame_video) except Exception as e: self._model.activity_logger.error(f"ModelSave.add_position_video_on_saved_image(): Error: {str(e)}")
[docs] def reopen_saved_image(self, parameter_name, file_name): """ Reopen saved image file Args: parameter_name file_name: Returns: """ try: if self._model.debug_mode: self._model.activity_logger.info("ModelSave: reopen_saved_image(), " "Reopen saved image to main application") # if self._model.timer.isActive(): # self._model.timer.stop() # self._model.timer_status.emit(self._model.timer.isActive()) self._model.image = cv2.imread(file_name) print("reopen_saved_image") self._model.calculate_resolution_option(self._model.image, self._model.ratio_resize) self._model.resize_image_param(parameter_name) self._model.load_saved_image = True self._model.signal_image_original.emit(self._model.image_resize) self._model.image_result.emit(self._model.image_resize) except Exception as e: self._model.activity_logger.error(f"ModelSave.reopen_saved_image(): Error: {str(e)}")
# def set_position_frame_save_image(self, config, file_name, original=False): # """ # This function sets the position of a saved frame from the `Image_saved` list in the configuration view. # If the timer is active, it will be stopped and the status will be emitted. If the parent path of the saved image # is the same as the media source, the position of the frame will be set and the next frame signal # will be emitted. If the parent path is different, the saved image will be reopened. # # Args: # config # file_name (str): The name of the saved file. # original (bool, optional): Flag to indicate if the view is in original or not. Defaults to False. # # # Returns: # None # """ # if self.model.timer.isActive(): # self.model.timer.stop() # self.model.timer_status.emit(self.model.timer.isActive()) # # if config["Image_saved"][file_name]["parent_path"] == self.model.media_source: # if config["Image_saved"][file_name]["is_video"]: # pos = config["Image_saved"][file_name]["pos_frame"] # self.model.cap.set(cv2.CAP_PROP_POS_FRAMES, pos) # if original: # self.model.state_recent_view = "FisheyeView" # self.model.next_frame_signal() # # else: # self.reopen_saved_image(config["Parameter_name"], file_name) # def re_run_after_load_saved_image(self, config): # """ # Performs necessary actions after loading a saved image, including updating the configuration file, resetting # certain attributes, and creating the original and result images. # # Returns: # None. # """ # self.model.load_saved_image = False # self.model.state_recent_view = "FisheyeView" # if isinstance(config["Media_path"], int): # self.model.timer.start(round(1000 / self.model.fps)) # # else: # self.model.create_image_original(config) # self.model.create_image_result(config) # # self.model.timer_status.emit(self.model.timer.isActive())
[docs] def clear_saved_image(self, config): """ Clear the saved image data from the configuration view and save the updated configuration to a file. This method removes all saved image data from the configuration view and updates the configuration file with the modified view. Args: self: The object instance. config Returns: None. Raises: IOError: An error occurred while writing the updated configuration to the file. """ try: if self._model.debug_mode: self._model.activity_logger.info("ModelSave: clear_saved_image(), " "Clear saved image on side windows and main config") config["Image_saved"] = {} with open(self._model.config_file, "w", encoding="utf-8") as outfile: yaml.dump(config, outfile, default_flow_style=False) except Exception as e: self._model.activity_logger.error(f"ModelSave.clear_saved_image(): Error: {str(e)}")