To create an easy-to-use graphical user interface (GUI) for the OCFR-2022 repository, we'll leverage PySimpleGUI, a Python library that simplifies GUI creation. This GUI will allow users to:
- Generate Aligned Data by selecting input and output directories and specifying image size.
- Select Occlusion Types by choosing a protocol (Protocol 1 or Protocol 3).
- Evaluate Face Recognition Models by specifying necessary directories and running evaluations.
Below is a step-by-step guide, including the complete Python script, to set up and use the GUI.
1. Prerequisites
Before running the GUI, ensure you have the necessary software and dependencies installed:
-
Python 3.x: Ensure Python is installed on your system. You can download it from python.org.
-
PySimpleGUI: Install via pip:
pip install PySimpleGUI
-
Other Dependencies: Ensure that all dependencies for align_db.py and evaluation.py are installed, such as opencv-python, numpy, etc. You can install them using:
pip install opencv-python numpy
-
OCFR-2022 Repository Scripts: Ensure that align_db.py, evaluation.py, and any other required scripts are present in your working directory or appropriately referenced.
2. GUI Script
Below is the complete Python script for the GUI, named ocfr_gui.py. This script provides a user-friendly interface to interact with the OCFR-2022 repository's functionalities.
import PySimpleGUI as sg
import subprocess
import os
# Define the layout for the GUI
def create_gui_layout():
sg.theme('LightBlue2') # Optional: Set a theme for the GUI
layout = [
[sg.Text('OCFR-2022 Repository GUI', font=('Any', 16), justification='center', expand_x=True)],
[sg.Frame(layout=[
[sg.Text('1. Generate Aligned Data', font=('Any', 14, 'underline'))],
[sg.Text('Input Directory:', size=(15,1)), sg.InputText(key='-ALIGN_INPUT_DIR-'), sg.FolderBrowse()],
[sg.Text('Output Directory:', size=(15,1)), sg.InputText(key='-ALIGN_OUTPUT_DIR-'), sg.FolderBrowse()],
[sg.Text('Image Size:', size=(15,1)), sg.InputText('112', key='-IMAGE_SIZE-', size=(10,1))],
[sg.Button('Generate Aligned Data', key='-GENERATE_ALIGNED-')]
], title='Step 1: Generating Aligned Data')],
[sg.HorizontalSeparator()],
[sg.Frame(layout=[
[sg.Text('2. Select Occlusion Types', font=('Any', 14, 'underline'))],
[sg.Text('Select Protocol:', size=(15,1)),
sg.Radio('Protocol 1 (Types 1,2,4)', "PROTOCOL", default=True, key='-PROTO1-'),
sg.Radio('Protocol 3 (Types 1-7,10-11)', "PROTOCOL", key='-PROTO3-')],
[sg.Button('Select Occlusion Types', key='-SELECT_OCCLUSION-')]
], title='Step 2: Selecting Occlusion Types')],
[sg.HorizontalSeparator()],
[sg.Frame(layout=[
[sg.Text('3. Evaluate Face Recognition Models', font=('Any', 14, 'underline'))],
[sg.Text('Evaluation Script:', size=(15,1)), sg.InputText('evaluation.py', key='-EVAL_SCRIPT-', size=(25,1)), sg.FileBrowse(file_types=(("Python Files","*.py"),))],
[sg.Text('Additional Arguments:', size=(15,1)), sg.InputText('--some-arg=value', key='-EVAL_ARGS-')],
[sg.Button('Run Evaluation', key='-RUN_EVALUATION-')]
], title='Step 3: Evaluating Face Recognition Models')],
[sg.HorizontalSeparator()],
[sg.Output(size=(80, 20))],
]
return sg.Window('OCFR-2022 GUI', layout, finalize=True)
# Function to generate aligned data
def generate_aligned_data(input_dir, output_dir, image_size):
try:
print("Generating aligned data...")
cmd = [
'python3', 'align_db.py',
'--input-dir', input_dir,
'--output-dir', output_dir,
'--image-size', str(image_size)
]
print(f"Running command: {' '.join(cmd)}")
subprocess.run(cmd, check=True)
print("Aligned data generation completed successfully.\n")
except subprocess.CalledProcessError as e:
print(f"Error during aligned data generation: {e}\n")
# Function to select occlusion types
def select_occlusion(protocol):
try:
print(f"Selecting occlusion types for {protocol}...")
# Here, you might need to modify a configuration file or set an environment variable
# depending on how occlusion types are handled in your scripts.
# For demonstration, we'll assume modifying a config file.
config_file = 'config.py' # Replace with your actual config file
if not os.path.exists(config_file):
print(f"Configuration file {config_file} not found.\n")
return
with open(config_file, 'r') as file:
lines = file.readlines()
with open(config_file, 'w') as file:
for line in lines:
if line.startswith('def select_occlusion_type'):
if protocol == 'Protocol 1':
new_func = """
def select_occlusion_type():
return np.random.choice([1, 2, 4])
"""
elif protocol == 'Protocol 3':
new_func = """
def select_occlusion_type():
return np.random.choice([1, 2, 4, 5, 6, 7, 10, 11])
"""
file.write(new_func)
else:
file.write(line)
print(f"Occlusion types set to {protocol} successfully.\n")
except Exception as e:
print(f"Error while selecting occlusion types: {e}\n")
# Function to run evaluation
def run_evaluation(script, args):
try:
print("Running evaluation script...")
cmd = [
'python3', script
]
if args:
cmd += args.split()
print(f"Running command: {' '.join(cmd)}")
subprocess.run(cmd, check=True)
print("Evaluation completed successfully.\n")
except subprocess.CalledProcessError as e:
print(f"Error during evaluation: {e}\n")
# Main function to execute the GUI
def main():
window = create_gui_layout()
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
elif event == '-GENERATE_ALIGNED-':
input_dir = values['-ALIGN_INPUT_DIR-']
output_dir = values['-ALIGN_OUTPUT_DIR-']
image_size = values['-IMAGE_SIZE-']
if not input_dir or not output_dir:
print("Please specify both input and output directories.\n")
else:
generate_aligned_data(input_dir, output_dir, image_size)
elif event == '-SELECT_OCCLUSION-':
if values['-PROTO1-']:
protocol = 'Protocol 1'
else:
protocol = 'Protocol 3'
select_occlusion(protocol)
elif event == '-RUN_EVALUATION-':
eval_script = values['-EVAL_SCRIPT-']
eval_args = values['-EVAL_ARGS-']
if not os.path.exists(eval_script):
print(f"Evaluation script {eval_script} does not exist.\n")
else:
run_evaluation(eval_script, eval_args)
window.close()
if __name__ == "__main__":
main()
3. Explanation of the GUI Components
3.1. Layout Structure
-
Title: Displays "OCFR-2022 Repository GUI" at the top.
-
Step 1: Generating Aligned Data
- Input Directory: Browse and select the directory containing raw input images.
- Output Directory: Browse and select where to save aligned and resized images.
- Image Size: Specify the target image size (default is
112).
- Generate Button: Triggers the alignment process.
-
Step 2: Selecting Occlusion Types
- Protocol Selection: Choose between Protocol 1 and Protocol 3.
- Select Button: Applies the selected occlusion protocol.
-
Step 3: Evaluating Face Recognition Models
- Evaluation Script: Browse and select the evaluation script (
evaluation.py by default).
- Additional Arguments: Specify any additional command-line arguments for the evaluation script.
- Run Button: Executes the evaluation script with the provided arguments.
-
Output Console: Displays real-time output and logs from the executed commands.
3.2. Functional Components
- Generate Aligned Data: Executes the
align_db.py script with user-specified parameters to preprocess and resize images.
- Select Occlusion Types: Modifies the
select_occlusion_type() function in a hypothetical config.py to set the desired occlusion protocol. Note: Ensure that your repository has a configuration mechanism that the GUI can modify. Adjust the select_occlusion function accordingly based on your project's actual structure.
- Run Evaluation: Executes the
evaluation.py script (or any specified evaluation script) with additional arguments provided by the user.
4. Usage Instructions
-
Save the Script: Save the above Python script as ocfr_gui.py in the root directory of your OCFR-2022 repository.
-
Ensure Script Accessibility:
- Ensure that
align_db.py, evaluation.py, and any other necessary scripts are in the same directory or appropriately referenced.
- If your scripts are located elsewhere, adjust the paths in the GUI script accordingly.
-
Run the GUI:
Open a terminal or command prompt, navigate to your repository's directory, and execute:
python3 ocfr_gui.py
-
Using the GUI:
-
Exit: Close the GUI window or click the window's close button to terminate the application.
5. Customization and Enhancements
-
Error Handling: The provided script includes basic error handling. Depending on your repository's complexity, you may need to enhance error checks, especially when modifying configuration files.
-
Configuration Management: The select_occlusion function assumes that there's a config.py file where the select_occlusion_type function is defined. Adjust this based on how your repository manages configurations.
-
Additional Features: You can further enhance the GUI by adding features such as:
- Progress bars to indicate long-running tasks.
- Logging mechanisms to save output logs to a file.
- Options to handle more steps or scripts from your repository.
-
Cross-Platform Compatibility: Ensure that the subprocess commands (like python3) are compatible with your operating system. On Windows, you might need to replace python3 with python.
6. Conclusion
This GUI provides a straightforward interface for users to interact with the OCFR-2022 repository's functionalities without needing to use the command line. By following the steps above, you can set up and customize the GUI to fit your specific workflow and repository structure.
Feel free to modify and expand the GUI to accommodate additional features or scripts as needed!