This repo hosts code for misc computer vision stuff for Eric's moth collections
The code in this repo is licensed under GNU GPLv3. The data belong to Eric F. LoPresti (University of South Carolina). Contact Eric F. LoPresti for any use of data in this repo.
Run Package_installation.R to install repository R dependencies. For the dependency vmisc, see vmisc GitHub page on installation instructions. All the poster processing / analysis and non-deeplearning related tasks can be done with with the R package.
To use the COCO-annotator, simply run, the following code after launching Docker desktop:
cd .\coco-annotator
start "firefox.exe" http://localhost:5000/
Call docker-compose upFor computer vision tasks that uses deeplearning or more expensive image manipulations that involve the predictions of Mask-R-CNN, the python dependencies need to be installed.
# Create conda environment to install stuff into
conda create -n "mothz" python=3.8.2
conda activate mothz
# Begin with detectron2 installations
# Check CUDA version
nvcc --version
# Find the right pytorch versions for the CUDA version installed https://pytorch.org/
# conda install pytorch==2.5.1 torchvision==0.20.1 torchaudio==2.5.1 pytorch-cuda=12.1 -c pytorch -c nvidia
python -m pip install -e detectron2 to install Detectron2
# Install Jupyter notbook
pip install jupyterlab
# Install other packages
pip install opencv-contrib-python numpy matplotlib tensorflow pytesseract
# I also installed some mothra dependencies but that is not required.
# see `detectron2/requirements.txt` for detectron2 requirements
# see `detectron2/SORT_requirements.txt` for SORT requirements (beetle tracking stuff)To do anything with python using the jupyter notebooks, run
cd .
Call conda activate mothz
Call jupyter labTo do anything with pytasseract,
# Follow instructions to install tesseract
# https://github.com/tesseract-ocr/tessdoc/blob/main/Installation.md
# Find out where `tesseract.exe` is installed.
# `read_img_tags()` and `read_text()` has an argument `tesseract_loc` where you can specify the location of the `tesseract.exe` file.
# Or do this for windows:
tesseract_loc = 'C:/Program Files/Tesseract-OCR/tesseract.exe'
pytesseract.pytesseract.tesseract_cmd = tesseract_locSome file manipulations may require the ExifTool software via the exifr package, but the package would ask you to install the program if it cannot be found.
There are two custom libraries used in this project, one written in R and the other in python.
This is a fork from the detectron2 package released by facebook. I've tried to avoid editing the package source code directly so that the installation would be less of a pain. The new code additions are added in detectron2/detectron2/custom/ and imported into the jupyter notebook as needed. If those functions are not imported, then the package should behave more or less the same as the version (v0.6) released.
The custom code written for this project are bundled as a pseudo simulated package mothr. It can be imported using vmisc::load_all2("mothr"), or pkgload::load_all("mothr") to enter developer mode. The latter mode allows newly recompiled C++ code to be included in the package, but copies the .dll file for each time it is initiated, which can cause memory overflow, especially in multi-session parallel computing.
- Image representations
cimg: RGB image tensor array from imager that represents an image in R. Can be used with functions from imager, imagerExtra, and mothr.pixset: Binary image tensor array from imager that represents binary masks in R. Can be used with functions from imager, imagerExtra, and mothr. Generic methods implemented in mothr includeplot(),area(),centroid(),as.polygon(),IOU().imlist: A list ofcimgorpixsetobjects.
- Annotation geometries
bbox: Bounding box encoded as a 2 X 2 matrix of lower left and top right corner coordinates. Has generic methods such asprint(),area(),centroid(),as.polygon(),as.pixset(),IOU(),plot().polygon: Polygon encoded as a n X 2 matrix of margin coordinates. This is a more efficient representation of binary masks (pixsetobjects). Has generic methods such asprint(),area(),centroid(),as.bbox(),as.pixset(),IOU(),plot().keypoint: keypoints encoded as n_keypoints X 3 matrix of keypoint coordinates and score or flag. Has generic methods such asprint(),plot().
- Detection instances
instance: One instance of object detection composed of a list of annotation geometries, instance_id, image_id, score, and thing_class. Has generic methods such asprint(),plot(),as.bbox(),as.pixset(),find_things(),find_labels().inlist: A list ofinstanceobjects associated with an image. Has generic methods such asprint(),[],c(),plot(),as.bbox(),as.pixset(),find_things(),find_labels().
- Annotation files
raw_inference: Raw inference file composed of the two .csv files created by detectron2. Can be converted toparsed_inferenceorCOCO_Jsonobjects.parsed_inference: A cleaned inference file formatted more like a COCO annotation file, but uses the nice tibble nested list function to store theinlistobjects as entries of image metadata, which is a tibble. Supports various COCO evaluators,bbox_evaluator(),mask_evaluator(), andkeypoint_evaluator(). This should be the primary format with which to interact with detectron2 predictions.COCO_Json: A list of data.frames and lists that represents a COCO annotation file. This is the file format that COCO annotator would take. Has functions forimport_COCO(),export_COCO(),split_COCO(),merge_COCO(),sample_COCO(),subset_COCO(),wipe_annotations_COCO(),update_manual_COCO(),set_new_path_COCO(),as.parsed_inference(),print(), andsummary().
Currently, Git is set to ignore the following directories (mainly due to file size limitations)
/coco-annotator/datasets
/graphs
/invisible
/detectron2/custom_trainingmothr/The root directory of the mothr package..Rfiles in this directory are not loaded in the package.mothr/R/Contains the R source codemothr/src/Contains the C++ source codemothr/assets/Contains data used for the functioning for the mothr packagecolor_index_formulas.csvDifferent RGB transformation formulas modified from pilmanexclude_flags.csvA single column of the file name of photos which should be excluded from analysis due to some error one way or another.historic_specimens.csvA single column of the file name of photos which are flagged as being from the historic specimens collection. Used for deciding which tag_id read output from the OCR module with different settings should be kept.image_database.csvA two-column table of the photo file_name to image_id mapping.inference_error.csvA two-column table of the file name of photos which should be excluded from analysis due to some problem with the computer vision inference and the inference model version number.real_tag_id.csvA two-column table of the photo file_name to tag_id mapping that has been manually entered. Overrides whatever the OCR system guesses the tag_id is in the photo.
DESCRIPTIONPackage description fileNAMESPACENamespace file.RbuildignoreWhat to ignore in building the mothr packagePackage_installation.Ra handy script to help you install mothr R dependencies.
archive/Old and obsolete scripts used to developmentcleaned_data/Stores cleaned datacoco-annotator/The folder for all coco-annotator related program filesCOCO_annotations/The folder for storing coco-annotator generated annotation filesmothz_sample1_fullset_keypoints.jsonSample 1 keypoint annotationsmothz_sample1_fullset_mask.jsonSample 1 mask annotationscoco_kp_test.jsonSample 1 testing data keypoint annotationscoco_mask_test.jsonSample 1 testing data mask annotationscoco_kp_train.jsonSample 1 training data keypoint annotationscoco_mask_train.jsonSample 1 training data mask annotationscoco_kp_val.jsonSample 1 validation data keypoint annotationscoco_mask_val.jsonSample 1 validation data mask annotations
detectron2/The folder for all detectron2 related program filesdoc/Some package and repo documentationinference/Stores inference output from the detectron2 pipelineall_batches/Stores inference output for the photo database.full_mothz_sample1_*Store inference output for sample 1 (including train, test, and val datasets).
misc/Misc scripts that are currently in use for something but not organized. These scripts are not part of any pipeline.raw_data/Stores raw datascripts/cleaning/Some scripts for cleaningmini_moth.RScript for generating cached mini_moth images for faster processingflagging.RScript for flagging photos
pre_inference_processing/Some scripts for pre-inference taskscoco_split.RScript for splitting the coco annotation file into training, testing, and validation datasetstraining_data_sample.RScript for sampling training data from the image database
post_inference_processing/Some scripts for post-inference tasksCOCO_evaluation.RScript for benchmarking the detectron2 modelmerge_inferences.RScript for merging and parsing the raw inferences for all batches
training_and_inference/Some scripts for training the detectron2 model and performing inference
README.mdThe thing that you are reading right now
- Run
scripts/training_and_inference/model_v1_kp_train.ipynbandscripts/training_and_inference/model_v1_mask_train.ipynbon new photos in the image database./moth_photos/database/. The new raw inference files should be written ininference/all_batches/. - Run the following,
parsed_mask <- import_raw_inference(path_meta = "inference/batch_*_image_meta_mask.csv",
path_inference = "inference/batch_*_inference_mask.csv") %>%
as.parsed_inference()
parsed_kp <- import_raw_inference(path_meta = "inference/batch_*_image_meta_keypoint.csv",
path_inference = "inference/batch_*_inference_keypoint.csv") %>%
as.parsed_inference()
my_object <- merge_parsed_inference(parsed_mask, parsed_kp)The my_object is a parsed_inference object that can then be used for further analyses.
- For analysis of images in R, it is faster to work with the cached mini moth files, which are generated from the original image cropped at the bounding box. Run
scripts/cleaning/mini_moth.Rto make those files.
Tad's Ice box has a slightly different launching procedure for python related stuff. I document the steps I took that got it to work.
First, enter the right directory then active the Conda environment:
cd ~/mothz
conda activate mothzWe want to expose the path of the correct CUDA installation:
export CUDA_HOME=/usr/local/cudaNow we can launch the jupyter notebook:
jupyter lab