class_docstr: The ``SemanticSegmentationData`` class is a :class:`~flash.core.data.data_module.DataModule` with a set of
  classmethods for loading data for semantic segmentation.
docstr: Load the :class:`~flash.image.segmentation.data.SemanticSegmentationData` from folders containing image files
  and folders containing mask files.
  
  The supported file extensions are: ``.jpg``, ``.jpeg``, ``.png``, ``.ppm``, ``.bmp``, ``.pgm``, ``.tif``,
  ``.tiff``, ``.webp``, and ``.npy``.
  For train, test, and validation data, the folders are expected to contain the images with a corresponding target
  folder which contains the mask in a file of the same name.
  For example, if your ``train_images`` folder (passed to the ``train_folder`` argument) looks like this:
  
  .. code-block::
  
      train_images
      ├── image_1.png
      ├── image_2.png
      ├── image_3.png
      ...
  
  your ``train_masks`` folder (passed to the ``train_target_folder`` argument) would need to look like this
  (although the file extensions could be different):
  
  .. code-block::
  
      train_masks
      ├── image_1.png
      ├── image_2.png
      ├── image_3.png
      ...
  
  For prediction, the folder is expected to contain the files for inference, like this:
  
  .. code-block::
  
      predict_folder
      ├── predict_image_1.png
      ├── predict_image_2.png
      ├── predict_image_3.png
      ...
  
  To learn how to customize the transforms applied for each stage, read our
  :ref:`customizing transforms guide <customizing_transforms>`.
  
  Args:
      train_folder: The folder containing images to use when training.
      train_target_folder: The folder containing masks to use when training (files should have the same name as
          the files in the ``train_folder``).
      val_folder: The folder containing images to use when validating.
      val_target_folder: The folder containing masks to use when validating (files should have the same name as
          the files in the ``train_folder``).
      test_folder: The folder containing images to use when testing.
      test_target_folder: The folder containing masks to use when testing (files should have the same name as
          the files in the ``train_folder``).
      predict_folder: The folder containing images to use when predicting.
      input_cls: The :class:`~flash.core.data.io.input.Input` type to use for loading the data.
      num_classes: The number of segmentation classes.
      labels_map: An optional mapping from class to RGB tuple indicating the colour to use when visualizing masks.
          If not provided, a random mapping will be used.
      transform: The :class:`~flash.core.data.io.input_transform.InputTransform` type to use.
      transform_kwargs: Dict of keyword arguments to be provided when instantiating the transforms.
      data_module_kwargs: Additional keyword arguments to provide to the
        :class:`~flash.core.data.data_module.DataModule` constructor.
  
  Returns:
      The constructed :class:`~flash.image.segmentation.data.SemanticSegmentationData`.
  
  Examples
  ________
  
  .. testsetup::
  
      >>> import os
      >>> from PIL import Image
      >>> rand_image = Image.fromarray(np.random.randint(0, 255, (64, 64, 3), dtype="uint8"))
      >>> rand_mask = Image.fromarray(np.random.randint(0, 10, (64, 64), dtype="uint8"))
      >>> os.makedirs("train_images", exist_ok=True)
      >>> os.makedirs("train_masks", exist_ok=True)
      >>> os.makedirs("predict_folder", exist_ok=True)
      >>> _ = [rand_image.save(os.path.join("train_images", f"image_{i}.png")) for i in range(1, 4)]
      >>> _ = [rand_mask.save(os.path.join("train_masks", f"image_{i}.png")) for i in range(1, 4)]
      >>> _ = [rand_image.save(os.path.join("predict_folder", f"predict_image_{i}.png")) for i in range(1, 4)]
  
  .. doctest::
  
      >>> from flash import Trainer
      >>> from flash.image import SemanticSegmentation, SemanticSegmentationData
      >>> datamodule = SemanticSegmentationData.from_folders(
      ...     train_folder="train_images",
      ...     train_target_folder="train_masks",
      ...     predict_folder="predict_folder",
      ...     transform_kwargs=dict(image_size=(128, 128)),
      ...     num_classes=10,
      ...     batch_size=2,
      ... )
      >>> datamodule.num_classes
      10
      >>> model = SemanticSegmentation(backbone="resnet18", num_classes=datamodule.num_classes)
      >>> trainer = Trainer(fast_dev_run=True)
      >>> trainer.fit(model, datamodule=datamodule)  # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
      Training...
      >>> trainer.predict(model, datamodule=datamodule)  # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
      Predicting...
  
  .. testcleanup::
  
      >>> import shutil
      >>> shutil.rmtree("train_images")
      >>> shutil.rmtree("train_masks")
      >>> shutil.rmtree("predict_folder")
docstr_tok: ["Load","the",":","class",":","`","~flash.image.segmentation.data.SemanticSegmentationData","`","from","folders","containing","image","files","and","folders","containing","mask","files",".","The","supported","file","extensions","are",":","``",".jpg","``",",","``",".jpeg","``",",","``",".png","``",",","``",".ppm","``",",","``",".bmp","``",",","``",".pgm","``",",","``",".tif","``",",","``",".tiff","``",",","``",".webp","``",",","and","``",".npy","``",".","For","train",",","test",",","and","validation","data",",","the","folders","are","expected","to","contain","the","images","with","a","corresponding","target","folder","which","contains","the","mask","in","a","file","of","the","same","name",".","For","example",",","if","your","``","train_images","``","folder","(","passed","to","the","``","train_folder","``","argument",")","looks","like","this",":","..","code-block",":",":","train_images","\u251c\u2500\u2500","image_1.png","\u251c\u2500\u2500","image_2.png","\u251c\u2500\u2500","image_3.png","...","your","``","train_masks","``","folder","(","passed","to","the","``","train_target_folder","``","argument",")","would","need","to","look","like","this","(","although","the","file","extensions","could","be","different",")",":","..","code-block",":",":","train_masks","\u251c\u2500\u2500","image_1.png","\u251c\u2500\u2500","image_2.png","\u251c\u2500\u2500","image_3.png","...","For","prediction",",","the","folder","is","expected","to","contain","the","files","for","inference",",","like","this",":","..","code-block",":",":","predict_folder","\u251c\u2500\u2500","predict_image_1.png","\u251c\u2500\u2500","predict_image_2.png","\u251c\u2500\u2500","predict_image_3.png","...","To","learn","how","to","customize","the","transforms","applied","for","each","stage",",","read","our",":","ref",":","`","customizing","transforms","guide","<","customizing_transforms",">","`",".","Args",":","train_folder",":","The","folder","containing","images","to","use","when","training",".","train_target_folder",":","The","folder","containing","masks","to","use","when","training","(","files","should","have","the","same","name","as","the","files","in","the","``","train_folder","``",")",".","val_folder",":","The","folder","containing","images","to","use","when","validating",".","val_target_folder",":","The","folder","containing","masks","to","use","when","validating","(","files","should","have","the","same","name","as","the","files","in","the","``","train_folder","``",")",".","test_folder",":","The","folder","containing","images","to","use","when","testing",".","test_target_folder",":","The","folder","containing","masks","to","use","when","testing","(","files","should","have","the","same","name","as","the","files","in","the","``","train_folder","``",")",".","predict_folder",":","The","folder","containing","images","to","use","when","predicting",".","input_cls",":","The",":","class",":","`","~flash.core.data.io.input.Input","`","type","to","use","for","loading","the","data",".","num_classes",":","The","number","of","segmentation","classes",".","labels_map",":","An","optional","mapping","from","class","to","RGB","tuple","indicating","the","colour","to","use","when","visualizing","masks",".","If","not","provided",",","a","random","mapping","will","be","used",".","transform",":","The",":","class",":","`","~flash.core.data.io.input_transform.InputTransform","`","type","to","use",".","transform_kwargs",":","Dict","of","keyword","arguments","to","be","provided","when","instantiating","the","transforms",".","data_module_kwargs",":","Additional","keyword","arguments","to","provide","to","the",":","class",":","`","~flash.core.data.data_module.DataModule","`","constructor",".","Returns",":","The","constructed",":","class",":","`","~flash.image.segmentation.data.SemanticSegmentationData","`",".","Examples","________","..","testsetup",":",":",">",">",">","import","os",">",">",">","from","PIL","import","Image",">",">",">","rand_image","=","Image.fromarray","(","np.random.randint","(","0",",","255",",","(","64",",","64",",","3",")",",","dtype=","''","uint8","''",")",")",">",">",">","rand_mask","=","Image.fromarray","(","np.random.randint","(","0",",","10",",","(","64",",","64",")",",","dtype=","''","uint8","''",")",")",">",">",">","os.makedirs","(","``","train_images","''",",","exist_ok=True",")",">",">",">","os.makedirs","(","``","train_masks","''",",","exist_ok=True",")",">",">",">","os.makedirs","(","``","predict_folder","''",",","exist_ok=True",")",">",">",">","_","=","[","rand_image.save","(","os.path.join","(","``","train_images","''",",","f","''","image_","{","i","}",".png","''",")",")","for","i","in","range","(","1",",","4",")","]",">",">",">","_","=","[","rand_mask.save","(","os.path.join","(","``","train_masks","''",",","f","''","image_","{","i","}",".png","''",")",")","for","i","in","range","(","1",",","4",")","]",">",">",">","_","=","[","rand_image.save","(","os.path.join","(","``","predict_folder","''",",","f","''","predict_image_","{","i","}",".png","''",")",")","for","i","in","range","(","1",",","4",")","]","..","doctest",":",":",">",">",">","from","flash","import","Trainer",">",">",">","from","flash.image","import","SemanticSegmentation",",","SemanticSegmentationData",">",">",">","datamodule","=","SemanticSegmentationData.from_folders","(","...","train_folder=","''","train_images","''",",","...","train_target_folder=","''","train_masks","''",",","...","predict_folder=","''","predict_folder","''",",","...","transform_kwargs=dict","(","image_size=","(","128",",","128",")",")",",","...","num_classes=10",",","...","batch_size=2",",","...",")",">",">",">","datamodule.num_classes","10",">",">",">","model","=","SemanticSegmentation","(","backbone=","''","resnet18","''",",","num_classes=datamodule.num_classes",")",">",">",">","trainer","=","Trainer","(","fast_dev_run=True",")",">",">",">","trainer.fit","(","model",",","datamodule=datamodule",")","#","doctest",":","+ELLIPSIS","+NORMALIZE_WHITESPACE","Training","...",">",">",">","trainer.predict","(","model",",","datamodule=datamodule",")","#","doctest",":","+ELLIPSIS","+NORMALIZE_WHITESPACE","Predicting","...","..","testcleanup",":",":",">",">",">","import","shutil",">",">",">","shutil.rmtree","(","``","train_images","''",")",">",">",">","shutil.rmtree","(","``","train_masks","''",")",">",">",">","shutil.rmtree","(","``","predict_folder","''",")"]
code: def from_folders(
      cls,
      train_folder: Optional[str] = None,
      train_target_folder: Optional[str] = None,
      val_folder: Optional[str] = None,
      val_target_folder: Optional[str] = None,
      test_folder: Optional[str] = None,
      test_target_folder: Optional[str] = None,
      predict_folder: Optional[str] = None,
      input_cls: Type[Input] = SemanticSegmentationFolderInput,
      num_classes: Optional[int] = None,
      labels_map: Dict[int, Tuple[int, int, int]] = None,
      transform: INPUT_TRANSFORM_TYPE = SemanticSegmentationInputTransform,
      transform_kwargs: Optional[Dict] = None,
      **data_module_kwargs: Any,
  ) -> "SemanticSegmentationData":
      """Load the :class:`~flash.image.segmentation.data.SemanticSegmentationData` from folders containing image files
      and folders containing mask files.
  
      The supported file extensions are: ``.jpg``, ``.jpeg``, ``.png``, ``.ppm``, ``.bmp``, ``.pgm``, ``.tif``,
      ``.tiff``, ``.webp``, and ``.npy``.
      For train, test, and validation data, the folders are expected to contain the images with a corresponding target
      folder which contains the mask in a file of the same name.
      For example, if your ``train_images`` folder (passed to the ``train_folder`` argument) looks like this:
  
      .. code-block::
  
          train_images
          ├── image_1.png
          ├── image_2.png
          ├── image_3.png
          ...
  
      your ``train_masks`` folder (passed to the ``train_target_folder`` argument) would need to look like this
      (although the file extensions could be different):
  
      .. code-block::
  
          train_masks
          ├── image_1.png
          ├── image_2.png
          ├── image_3.png
          ...
  
      For prediction, the folder is expected to contain the files for inference, like this:
  
      .. code-block::
  
          predict_folder
          ├── predict_image_1.png
          ├── predict_image_2.png
          ├── predict_image_3.png
          ...
  
      To learn how to customize the transforms applied for each stage, read our
      :ref:`customizing transforms guide <customizing_transforms>`.
  
      Args:
          train_folder: The folder containing images to use when training.
          train_target_folder: The folder containing masks to use when training (files should have the same name as
              the files in the ``train_folder``).
          val_folder: The folder containing images to use when validating.
          val_target_folder: The folder containing masks to use when validating (files should have the same name as
              the files in the ``train_folder``).
          test_folder: The folder containing images to use when testing.
          test_target_folder: The folder containing masks to use when testing (files should have the same name as
              the files in the ``train_folder``).
          predict_folder: The folder containing images to use when predicting.
          input_cls: The :class:`~flash.core.data.io.input.Input` type to use for loading the data.
          num_classes: The number of segmentation classes.
          labels_map: An optional mapping from class to RGB tuple indicating the colour to use when visualizing masks.
              If not provided, a random mapping will be used.
          transform: The :class:`~flash.core.data.io.input_transform.InputTransform` type to use.
          transform_kwargs: Dict of keyword arguments to be provided when instantiating the transforms.
          data_module_kwargs: Additional keyword arguments to provide to the
            :class:`~flash.core.data.data_module.DataModule` constructor.
  
      Returns:
          The constructed :class:`~flash.image.segmentation.data.SemanticSegmentationData`.
  
      Examples
      ________
  
      .. testsetup::
  
          >>> import os
          >>> from PIL import Image
          >>> rand_image = Image.fromarray(np.random.randint(0, 255, (64, 64, 3), dtype="uint8"))
          >>> rand_mask = Image.fromarray(np.random.randint(0, 10, (64, 64), dtype="uint8"))
          >>> os.makedirs("train_images", exist_ok=True)
          >>> os.makedirs("train_masks", exist_ok=True)
          >>> os.makedirs("predict_folder", exist_ok=True)
          >>> _ = [rand_image.save(os.path.join("train_images", f"image_{i}.png")) for i in range(1, 4)]
          >>> _ = [rand_mask.save(os.path.join("train_masks", f"image_{i}.png")) for i in range(1, 4)]
          >>> _ = [rand_image.save(os.path.join("predict_folder", f"predict_image_{i}.png")) for i in range(1, 4)]
  
      .. doctest::
  
          >>> from flash import Trainer
          >>> from flash.image import SemanticSegmentation, SemanticSegmentationData
          >>> datamodule = SemanticSegmentationData.from_folders(
          ...     train_folder="train_images",
          ...     train_target_folder="train_masks",
          ...     predict_folder="predict_folder",
          ...     transform_kwargs=dict(image_size=(128, 128)),
          ...     num_classes=10,
          ...     batch_size=2,
          ... )
          >>> datamodule.num_classes
          10
          >>> model = SemanticSegmentation(backbone="resnet18", num_classes=datamodule.num_classes)
          >>> trainer = Trainer(fast_dev_run=True)
          >>> trainer.fit(model, datamodule=datamodule)  # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
          Training...
          >>> trainer.predict(model, datamodule=datamodule)  # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
          Predicting...
  
      .. testcleanup::
  
          >>> import shutil
          >>> shutil.rmtree("train_images")
          >>> shutil.rmtree("train_masks")
          >>> shutil.rmtree("predict_folder")
  
      """
  
      ds_kw = {
          "num_classes": num_classes,
          "labels_map": labels_map,
      }
  
      return cls(
          input_cls(
              RunningStage.TRAINING,
              train_folder,
              train_target_folder,
              **ds_kw,
          ),
          input_cls(
              RunningStage.VALIDATING,
              val_folder,
              val_target_folder,
              **ds_kw,
          ),
          input_cls(
              RunningStage.TESTING,
              test_folder,
              test_target_folder,
              **ds_kw,
          ),
          input_cls(RunningStage.PREDICTING, predict_folder, **ds_kw),
          transform=transform,
          transform_kwargs=transform_kwargs,
          **data_module_kwargs,
      )
  
imports: from typing import Any, Collection, Dict, Optional, Sequence, Tuple, Type
  import numpy
  from torch import Tensor
  from flash.core.data.callback import BaseDataFetcher
  from flash.core.data.data_module import DataModule
  from flash.core.data.io.input import Input
  from flash.core.utilities.imports import _FIFTYONE_AVAILABLE, _SEGMENTATION_MODELS_AVAILABLE, lazy_import
  from flash.core.utilities.stages import RunningStage
  from flash.core.utilities.types import INPUT_TRANSFORM_TYPE
  from flash.image.segmentation.input import SemanticSegmentationFiftyOneInput, SemanticSegmentationFilesInput, SemanticSegmentationFolderInput, SemanticSegmentationNumpyInput, SemanticSegmentationTensorInput
  from flash.image.segmentation.input_transform import SemanticSegmentationInputTransform
  from flash.image.segmentation.viz import SegmentationMatplotlibVisualization
label_desc: Use image node_id 3 for calling the SemanticSegmentationData obj's underlying member method code with example usage: obj.from_folders(cls, train_folder, train_target_folder, val_folder, val_target_folder, test_folder, test_target_folder, predict_folder, input_cls, num_classes, labels_map, transform, transform_kwargs) and returns: cls