Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
northumber authored Jan 11, 2024
1 parent 2f2a4f5 commit 7061585
Show file tree
Hide file tree
Showing 5 changed files with 255 additions and 0 deletions.
3 changes: 3 additions & 0 deletions changelog.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## 1.0.0

- Program created and distributed
100 changes: 100 additions & 0 deletions person_autocrop.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import os
import cv2
import numpy as np
import tensorflow as tf
import gdown

# Download model if not exist
def download_model():
url = f"https://drive.google.com/uc?id=1Ml260620LIKa-OrWqdzv_z99NJKixt3W"
gdown.download(url, "ssd_mobilenetv2_coco/saved_model.pb", quiet=False)

# Explicitly specify the GPU device
physical_devices = tf.config.list_physical_devices('GPU')
if len(physical_devices) > 0:
tf.config.experimental.set_memory_growth(physical_devices[0], True)

# Initialize model variable
model = None

def create_folder(output_directory):
# Check if the folder exists
if not os.path.exists(output_directory):
try:
# Create the folder if it doesn't exist
os.makedirs(output_directory)
print(f"LOG: Folder '{output_directory}' created successfully.")
except OSError as e:
print(f"LOG: Error creating folder '{output_directory}': {e}")

# Function to perform object detection and crop the image
def object_detection(input_image_path, output_directory):

# Read the input image
image = cv2.imread(input_image_path)
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image_expanded = np.expand_dims(image_rgb, axis=0).astype(np.uint8)

# Perform inference
detections = model.signatures["serving_default"](tf.constant(image_expanded))

# Extract coordinates of detected persons
detection_classes = detections['detection_classes'][0].numpy()
detection_boxes = detections['detection_boxes'][0]
person_indices = tf.where(tf.equal(detection_classes, 1))[:, 0]
person_coords = tf.gather(detection_boxes, person_indices).numpy()

# Crop the original image based on the detected persons' coordinates
for i, coords in enumerate(person_coords):
ymin, xmin, ymax, xmax = coords

# Ensure valid coordinates
if 0 <= ymin < ymax <= image.shape[0] and 0 <= xmin < xmax <= image.shape[1]:
ymin, xmin, ymax, xmax = (
int(ymin * image.shape[0]),
int(xmin * image.shape[1]),
int(ymax * image.shape[0]),
int(xmax * image.shape[1]),
)
cropped_person = image[ymin:ymax, xmin:xmax, :]

# Check if the cropped_person array is not empty
if not cropped_person.size == 0:
# Save the cropped person image with correct color space conversion
try:
image_name = os.path.basename(input_image_path)
# Save the image using cv2.imwrite()
cv2.imwrite(f"{output_directory}/{i + 1}_{image_name}", cropped_person)
print(f"LOG: Image saved successfully to '{output_directory}/{i + 1}_{image_name}'.")
except Exception as e:
print(f"LOG: Error saving image: {e}")
else:
print(f"LOG: Warning: Cropped person {i + 1} is empty.")

if __name__ == "__main__":
import sys

if len(sys.argv) != 3:
print("Usage: python person_crop.py <input_image_folder> <output_directory>")
sys.exit(1)

input_image_folder = sys.argv[1]
output_directory = sys.argv[2]

if os.path.exists("ssd_mobilenetv2_coco/saved_model.pb"):
print("LOG: SSD Mobilenet V2 COCO model found.")
else:
print("LOG: SSD Mobilenet V2 COCO model not found. Downloading...")
download_model()
print("LOG: SSD Mobilenet V2 COCO model downloaded.")

model = tf.saved_model.load("ssd_mobilenetv2_coco")
create_folder(output_directory)

print("LOG: Running...")
# Process all images in the input folder
for filename in os.listdir(input_image_folder):
if filename.endswith(".jpg") or filename.endswith(".png") or filename.endswith(".jpeg") or filename.endswith(".webp") or filename.endswith(".bmp"):
input_image_path = os.path.join(input_image_folder, filename)
object_detection(input_image_path, output_directory)
print("LOG: Done.")
4 changes: 4 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
opencv-python
numpy
tensorflow
gdown
73 changes: 73 additions & 0 deletions run.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
@echo off

set VENV_FOLDER=venv
set REQUIREMENTS_FILE=requirements.txt

rem Check if virtual environment folder exists
if not exist %VENV_FOLDER% (
echo LOG: Virtual environment not found. Creating...
python -m venv %VENV_FOLDER%
echo LOG: Virtual environment created.
)

rem Activate the virtual environment
call %VENV_FOLDER%\Scripts\activate

echo LOG: Virtual environment is activated.
echo LOG: Checking if pip is in VENV.
rem Check if pip is installed in the virtual environment
pip --version >nul 2>&1
if %errorlevel% neq 0 (
echo LOG: Installing pip in the virtual environment...
python -m ensurepip
echo LOG: pip successfully installed.
)

rem Check if requirements are already installed
set "REQUIREMENTS_MET=true"
for /f "delims=" %%i in (%REQUIREMENTS_FILE%) do (
set "PACKAGE_FOUND=false"
)

for /d %%p in (%VENV_FOLDER%\Lib\site-packages\*) do (
for /f %%i in ('type %REQUIREMENTS_FILE% ^| findstr /i /c:"%%~nxp"') do (
set "PACKAGE_FOUND=true"
goto :PACKAGE_FOUND
)
)
:PACKAGE_FOUND

if "%PACKAGE_FOUND%"=="false" (
set "REQUIREMENTS_MET=false"
echo LOG: Some requirements are missing.
)

if "%REQUIREMENTS_MET%"=="false" (
echo LOG: Installing requirements...
pip install -r %REQUIREMENTS_FILE%
) else (
echo LOG: Requirements are already installed.
)

set "modelfolder=ssd_mobilenetv2_coco"

rem Check if the folder exists
if not exist "%modelfolder%" (
echo LOG: Model folder does not exist. Creating...
mkdir "%modelfolder%"
if errorlevel 1 (
echo LOG: Failed to create model folder. Aborting.
exit /b 1
) else (
echo LOG: Model folder created successfully.
)
)

echo.
set /p INPUT_FOLDER="-> Enter input image folder path: "
set /p OUTPUT_FOLDER="-> Enter output image folder path: "

echo.
echo LOG: Running the script
rem Run the Python script
python person_autocrop.py %INPUT_FOLDER% %OUTPUT_FOLDER%
75 changes: 75 additions & 0 deletions run.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#!/bin/bash

VENV_FOLDER="venv"
REQUIREMENTS_FILE="requirements.txt"

# Check if virtual environment folder exists
if [ ! -d "$VENV_FOLDER" ]; then
echo "LOG: Virtual environment not found. Creating..."
python3 -m venv "$VENV_FOLDER"
echo "LOG: Virtual environment created."
fi

# Activate the virtual environment
source "$VENV_FOLDER/bin/activate"

echo "LOG: Virtual environment is activated."
echo "LOG: Checking if pip is in VENV."

# Check if pip is installed in the virtual environment
pip --version > /dev/null 2>&1
if [ $? -ne 0 ]; then
echo "LOG: Installing pip in the virtual environment..."
python -m ensurepip
echo "LOG: pip successfully installed."
fi

# Check if requirements are already installed
REQUIREMENTS_MET=true
while IFS= read -r req; do
PACKAGE_FOUND=false
done < "$REQUIREMENTS_FILE"

for package in "$VENV_FOLDER/lib/python*/site-packages/"*; do
while IFS= read -r req; do
if [[ "$package" == *"$req"* ]]; then
PACKAGE_FOUND=true
break
fi
done < "$REQUIREMENTS_FILE"
done

if [ "$PACKAGE_FOUND" == "false" ]; then
REQUIREMENTS_MET=false
echo "LOG: Some requirements are missing."
fi

if [ "$REQUIREMENTS_MET" == "false" ]; then
echo "LOG: Installing requirements..."
pip install -r "$REQUIREMENTS_FILE"
else
echo "LOG: Requirements are already installed."
fi

MODELFOLDER="ssd_mobilenetv2_coco"

# Check if the folder exists
if [ ! -d "$MODELFOLDER" ]; then
echo "LOG: Model folder does not exist. Creating..."
mkdir "$MODELFOLDER"
if [ $? -ne 0 ]; then
echo "LOG: Failed to create model folder. Aborting."
exit 1
else
echo "LOG: Model folder created successfully."
fi
fi

echo ""
read -p "-> Enter input image folder path: " INPUT_FOLDER
read -p "-> Enter output image folder path: " OUTPUT_FOLDER

echo ""
echo "LOG: Running the script"
# Run the Python script
python person_autocrop.py "$INPUT_FOLDER" "$OUTPUT_FOLDER"

0 comments on commit 7061585

Please sign in to comment.