Skip to content

Instantly share code, notes, and snippets.

@moi90
Last active November 25, 2020 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moi90/6308ba5ff79c80a0edc1611c3056b085 to your computer and use it in GitHub Desktop.
Save moi90/6308ba5ff79c80a0edc1611c3056b085 to your computer and use it in GitHub Desktop.
Process flowcam images using MorphoCut
import os.path
from morphocut import Call, Pipeline
from morphocut.contrib.ecotaxa import EcotaxaWriter
from morphocut.contrib.zooprocess import CalculateZooProcessFeatures
from morphocut.file import Glob
from morphocut.image import FindRegions, ImageReader, RGB2Gray
from morphocut.parallel import ParallelPipeline
from morphocut.str import Format
from morphocut.stream import Enumerate, Unpack
# First, a Pipeline is defined that contains all operations
# that should be carried out on the objects of the stream.
with Pipeline() as p:
pattern = "path/to/your/input/files/*.jpg"
# Corresponds to `for path in glob(pattern):`
path = Glob(pattern)
# Remove path and extension from the filename
source_basename = Call(lambda x: os.path.splitext(os.path.basename(x))[0], path)
with ParallelPipeline():
# The following operations are distributed among multiple
# worker processes to speed up the calculations.
# Read the image
image = ImageReader(path)
# Convert to gray
image_gray = RGB2Gray(image)
# Calculate threshold
def calc_threshold(img):
return 0.9*np.median(img)
threshold = Call(calc_threshold, image_gray)
# Do some thresholding
mask = image < threshold
# Find regions in the image
region = FindRegions(mask, image)
# Extract just the object
roi_image = region.intensity_image
# An object is identified by its label
roi_label = region.label
# Calculate a filename for the ROI image:
# "RUNNING_NUMBER-SOURCE_BASENAME-ROI_LABEL"
roi_name = Format(
"{:d}-{}-{:d}.jpg", running_number, source_basename, roi_label
)
meta = CalculateZooProcessFeatures(region, prefix="object_")
# End of parallel execution
# Store results
EcotaxaWriter("archive.zip", (roi_name, roi_image), meta)
# After the Pipeline was defined, it can be executed.
# A stream is created and transformed by the operations
# defined in the Pipeline.
p.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment