Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Call this function to launch a napari window with a given image to begin annotating true positives, false positives, and false negatives on the image with points layers.
import os
import napari
from skimage.io import imread, imsave
def napari_count_tfpn(screenshot_file, point_size=20, save_screenshot=True):
"""
Opens a napari window and initializes three points layers:
- "True Positives" with green points
- "False Positives" with red points
- "False Negatives" with yellow points
The user is then able to annotate their image with the points to count instances of each class in the image provided
by the "screenshot_file" parameter.
To complete the count, close the napari window. A dictionary is returned with counts for true positives, false
positives, and false negatives.
"tfpn" stands for true/false postive/negative and is a terrible function name. I am open to better alternatives.
Note that this script has dependencies as shown below:
import os
import napari
from skimage.io import imread, imsave
:param screenshot_file: (string) Path to image you wish to count true and false positive and negatives for.
:param point_size: (int) Size of points to use for annotations in napari.
:param save_screenshot" (bool) Whether or not to save a screenshot of the annotated image in the same location
as the original image, with "_Annotated" added to the filename before the file extension.
:return: A dictionary with tallies for true positives, false positives, and false negatives.
"""
screenshot_file = os.path.abspath(screenshot_file)
screenshot_directory = os.path.dirname(screenshot_file)
screenshot_filename = os.path.basename(screenshot_file)
screenshot_annotated = os.path.join(screenshot_directory, screenshot_filename.replace('.', '_Annotated.'))
try:
with napari.gui_qt():
viewer = napari.view_image(imread(screenshot_file), rgb=True)
TP_layer = viewer.add_points(size=point_size, name='True Positives', face_color='green')
FP_layer = viewer.add_points(size=point_size, name='False Positives', face_color='red')
FN_layer = viewer.add_points(size=point_size, name='False Negatives', face_color='yellow')
TP_layer.mode = 'add'
FP_layer.mode = 'add'
FN_layer.mode = 'add'
TP_layer.selected = True
FP_layer.selected = False
FN_layer.selected = False
finally:
tfpn_stats = {'True Positives': len(TP_layer.data),
'False Positives': len(FP_layer.data),
'False Negatives': len(FN_layer.data)}
if save_screenshot is True:
imsave(screenshot_annotated, viewer.screenshot())
return tfpn_stats
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment