Search in sources :

Example 26 with PathClass

use of qupath.lib.objects.classes.PathClass in project qupath by qupath.

the class RetainedTrainingObjects method put.

Map<PathClass, List<PathObject>> put(final String key, final Map<PathClass, List<PathObject>> value) {
    if (key == null)
        throw new IllegalArgumentException("Cannot retain objects without a key! Do you have a project open?");
    // Also, we create a new map to ensure it's sorted
    Map<PathClass, List<PathObject>> newMap = new TreeMap<>();
    for (PathClass pathClass : value.keySet()) {
        List<PathObject> originalList = value.get(pathClass);
        List<PathObject> newList = originalList.stream().map(p -> {
            if (p.isDetection())
                return PathObjects.createDetectionObject(p.getROI(), p.getPathClass(), p.getMeasurementList());
            else {
                logger.debug("Adding non-detection object to retained map: {}", p);
                return p;
            }
        }).collect(Collectors.toList());
        newMap.put(pathClass, newList);
        value.put(pathClass, newList);
    }
    return retainedObjectsMap.put(key, value);
}
Also used : Logger(org.slf4j.Logger) Externalizable(java.io.Externalizable) ObjectOutput(java.io.ObjectOutput) PathObjects(qupath.lib.objects.PathObjects) LoggerFactory(org.slf4j.LoggerFactory) PathClass(qupath.lib.objects.classes.PathClass) IOException(java.io.IOException) HashMap(java.util.HashMap) PathClassFactory(qupath.lib.objects.classes.PathClassFactory) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) PathObject(qupath.lib.objects.PathObject) List(java.util.List) TreeMap(java.util.TreeMap) Map(java.util.Map) Entry(java.util.Map.Entry) ObjectInput(java.io.ObjectInput) Collections(java.util.Collections) PathClass(qupath.lib.objects.classes.PathClass) PathObject(qupath.lib.objects.PathObject) ArrayList(java.util.ArrayList) List(java.util.List) TreeMap(java.util.TreeMap)

Example 27 with PathClass

use of qupath.lib.objects.classes.PathClass in project qupath by qupath.

the class PathIntensityClassifierPane method getIntensityClassifier.

/**
 * Returns a PathIntensityClassifier, or null if none was requested by the user's interactions with this JPanel.
 * @return
 */
public PathObjectClassifier getIntensityClassifier() {
    String intensityMeasurement = comboIntensities.getSelectionModel().getSelectedItem();
    PathObjectClassifier intensityClassifier = null;
    if (intensityMeasurement != null && !intensityMeasurement.equals("None")) {
        boolean singleThreshold = paramsIntensity.getBooleanParameterValue("single_threshold");
        double t1 = paramsIntensity.getDoubleParameterValue("threshold_1");
        // PathClass baseClass = PathClassFactory.getDefaultPathClass(PathClassFactory.PathClasses.TUMOR);
        PathClass baseClass = null;
        if (singleThreshold) {
            intensityClassifier = PathClassifierTools.createIntensityClassifier(baseClass, intensityMeasurement, t1);
        } else {
            double t2 = Math.max(t1, paramsIntensity.getDoubleParameterValue("threshold_2"));
            double t3 = Math.max(t2, paramsIntensity.getDoubleParameterValue("threshold_3"));
            intensityClassifier = PathClassifierTools.createIntensityClassifier(baseClass, intensityMeasurement, t1, t2, t3);
        }
    }
    return intensityClassifier;
}
Also used : PathClass(qupath.lib.objects.classes.PathClass) PathObjectClassifier(qupath.lib.classifiers.PathObjectClassifier)

Example 28 with PathClass

use of qupath.lib.objects.classes.PathClass in project qupath by qupath.

the class TestPixelClassifierTools method checkCreateObjects.

private void checkCreateObjects(ImageServer<BufferedImage> server, int[] hist, Map<PathClass, Integer> classificationLabelsReverse) throws IOException {
    var hierarchy = new PathObjectHierarchy();
    boolean success = PixelClassifierTools.createObjectsFromPredictions(server, hierarchy, Collections.singleton(hierarchy.getRootObject()), r -> PathObjects.createAnnotationObject(r), 0, 0);
    assertTrue(success);
    // Recall that we have an object for zero as well
    var annotations = new ArrayList<>(hierarchy.getAnnotationObjects());
    assertEquals(hist.length, annotations.size());
    // Check areas for all our annotations
    Collections.sort(annotations, Comparator.comparingInt(a -> classificationLabelsReverse.get(a.getPathClass())));
    for (var annotation : annotations) {
        int label = classificationLabelsReverse.get(annotation.getPathClass());
        var roi = annotation.getROI();
        double area = roi.getArea();
        if (printAreas)
            logger.debug(hist[label] + ": \t" + area);
        assertEquals(hist[label], area);
        var geom = roi.getGeometry();
        if (alwaysCheckValidity || geom.getNumPoints() < MAX_POINTS_FOR_VALIDITY) {
            var error = new IsValidOp(geom).getValidationError();
            if (error != null)
                logger.warn("{}", error);
            assertNull(error);
        }
        assertEquals(hist[label], geom.getArea());
    }
}
Also used : CreateObjectOptions(qupath.opencv.ml.pixel.PixelClassifierTools.CreateObjectOptions) RoiLabeling(qupath.imagej.processing.RoiLabeling) Arrays(java.util.Arrays) ImageServer(qupath.lib.images.servers.ImageServer) ByteProcessor(ij.process.ByteProcessor) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) PathClassFactory(qupath.lib.objects.classes.PathClassFactory) PathObjectHierarchy(qupath.lib.objects.hierarchy.PathObjectHierarchy) DataBufferByte(java.awt.image.DataBufferByte) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) ImageStatistics(ij.process.ImageStatistics) ChannelType(qupath.lib.images.servers.ImageServerMetadata.ChannelType) Map(java.util.Map) ImageIO(javax.imageio.ImageIO) ImageServers(qupath.lib.images.servers.ImageServers) Path(java.nio.file.Path) MethodSource(org.junit.jupiter.params.provider.MethodSource) IsValidOp(org.locationtech.jts.operation.valid.IsValidOp) Logger(org.slf4j.Logger) BufferedImage(java.awt.image.BufferedImage) PathObjects(qupath.lib.objects.PathObjects) PathClass(qupath.lib.objects.classes.PathClass) IOException(java.io.IOException) UUID(java.util.UUID) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Assertions(org.junit.jupiter.api.Assertions) WrappedBufferedImageServer(qupath.lib.images.servers.WrappedBufferedImageServer) Comparator(java.util.Comparator) Collections(java.util.Collections) ImageServerMetadata(qupath.lib.images.servers.ImageServerMetadata) PathObjectHierarchy(qupath.lib.objects.hierarchy.PathObjectHierarchy) ArrayList(java.util.ArrayList) IsValidOp(org.locationtech.jts.operation.valid.IsValidOp)

Example 29 with PathClass

use of qupath.lib.objects.classes.PathClass in project qupath by qupath.

the class DistanceTools method detectionCentroidDistances.

/**
 * Compute the distance for all detection object centroids to the closest annotation with each valid, not-ignored classification and add
 * the result to the detection measurement list.
 * @param imageData
 * @param splitClassNames if true, split the classification name. For example, if an image contains classifications for both "CD3: CD4" and "CD3: CD8",
 *                        distances will be calculated for all components (e.g. "CD3", "CD4" and "CD8").
 */
public static void detectionCentroidDistances(ImageData<?> imageData, boolean splitClassNames) {
    var server = imageData.getServer();
    var hierarchy = imageData.getHierarchy();
    var detections = hierarchy.getCellObjects();
    if (detections.isEmpty())
        detections = hierarchy.getDetectionObjects();
    // TODO: Support TMA cores
    if (hierarchy.getTMAGrid() != null)
        logger.warn("Detection centroid distances command currently ignores TMA grid information!");
    var pathClasses = detections.stream().map(p -> p.getPathClass()).filter(p -> p != null && p.isValid() && !PathClassTools.isIgnoredClass(p)).collect(Collectors.toSet());
    var cal = server.getPixelCalibration();
    String xUnit = cal.getPixelWidthUnit();
    String yUnit = cal.getPixelHeightUnit();
    double pixelWidth = cal.getPixelWidth().doubleValue();
    double pixelHeight = cal.getPixelHeight().doubleValue();
    if (!xUnit.equals(yUnit))
        throw new IllegalArgumentException("Pixel width & height units do not match! Width " + xUnit + ", height " + yUnit);
    String unit = xUnit;
    for (PathClass pathClass : pathClasses) {
        if (splitClassNames) {
            var names = PathClassTools.splitNames(pathClass);
            for (var name : names) {
                logger.debug("Computing distances for {}", pathClass);
                var filteredDetections = detections.stream().filter(a -> PathClassTools.containsName(a.getPathClass(), name)).collect(Collectors.toList());
                if (!filteredDetections.isEmpty()) {
                    String measurementName = "Distance to detection with " + name + " " + unit;
                    centroidToCentroidDistance2D(detections, filteredDetections, pixelWidth, pixelHeight, measurementName);
                }
            }
        } else {
            logger.debug("Computing distances for {}", pathClass);
            var filteredDetections = detections.stream().filter(a -> a.getPathClass() == pathClass).collect(Collectors.toList());
            if (!filteredDetections.isEmpty()) {
                String name = "Distance to detection " + pathClass + " " + unit;
                centroidToCentroidDistance2D(detections, filteredDetections, pixelWidth, pixelHeight, name);
            }
        }
    }
    hierarchy.fireObjectMeasurementsChangedEvent(DistanceTools.class, detections);
}
Also used : PointOnGeometryLocator(org.locationtech.jts.algorithm.locate.PointOnGeometryLocator) PathClassTools(qupath.lib.objects.classes.PathClassTools) PointPairDistance(org.locationtech.jts.algorithm.distance.PointPairDistance) LoggerFactory(org.slf4j.LoggerFactory) Coordinate(org.locationtech.jts.geom.Coordinate) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) Location(org.locationtech.jts.geom.Location) Puntal(org.locationtech.jts.geom.Puntal) DistanceToPoint(org.locationtech.jts.algorithm.distance.DistanceToPoint) GeometryTools(qupath.lib.roi.GeometryTools) AffineTransformation(org.locationtech.jts.geom.util.AffineTransformation) GeometryCombiner(org.locationtech.jts.geom.util.GeometryCombiner) ImageData(qupath.lib.images.ImageData) ItemBoundable(org.locationtech.jts.index.strtree.ItemBoundable) Logger(org.slf4j.Logger) Collection(java.util.Collection) PathClass(qupath.lib.objects.classes.PathClass) IndexedPointInAreaLocator(org.locationtech.jts.algorithm.locate.IndexedPointInAreaLocator) Polygonal(org.locationtech.jts.geom.Polygonal) Collectors(java.util.stream.Collectors) Lineal(org.locationtech.jts.geom.Lineal) PathObjectTools(qupath.lib.objects.PathObjectTools) PathObject(qupath.lib.objects.PathObject) List(java.util.List) Geometry(org.locationtech.jts.geom.Geometry) PrecisionModel(org.locationtech.jts.geom.PrecisionModel) Envelope(org.locationtech.jts.geom.Envelope) ItemDistance(org.locationtech.jts.index.strtree.ItemDistance) STRtree(org.locationtech.jts.index.strtree.STRtree) PathClass(qupath.lib.objects.classes.PathClass)

Example 30 with PathClass

use of qupath.lib.objects.classes.PathClass in project qupath by qupath.

the class ClassifierBuilderPane method exportTrainingFeatures.

private boolean exportTrainingFeatures(final File file) {
    // First, add existing objects to map
    ImageData<?> imageData = getImageData();
    // Get the features to export
    List<String> features = featurePanel.getSelectedFeatures();
    // Write the header
    PrintWriter writer;
    try {
        writer = new PrintWriter(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;
    }
    boolean includePath = !retainedObjectsMap.isEmpty();
    // String delim = "\t";
    String delim = ",";
    if (includePath) {
        writer.print("Image");
        writer.print(delim);
    }
    writer.print("Class");
    for (String feature : features) {
        writer.print(delim);
        // Make sure we replace the delimiter so we don't have trouble
        writer.print(feature.replace(delim, "-"));
    }
    writer.println();
    // Write the current objects
    String currentPath = null;
    if (imageData != null) {
        currentPath = imageData.getServerPath();
        Map<PathClass, List<PathObject>> map = getTrainingMap();
        for (Entry<PathClass, List<PathObject>> entry : map.entrySet()) {
            for (PathObject pathObject : entry.getValue()) {
                if (includePath) {
                    writer.print(currentPath);
                    writer.print(delim);
                }
                writer.print(entry.getKey().getName());
                writer.print(delim);
                for (String name : features) {
                    writer.print(Double.toString(pathObject.getMeasurementList().getMeasurementValue(name)));
                    writer.print(delim);
                }
                writer.println();
            }
        }
    }
    writer.close();
    return true;
}
Also used : PathClass(qupath.lib.objects.classes.PathClass) PathObject(qupath.lib.objects.PathObject) FileNotFoundException(java.io.FileNotFoundException) ParameterList(qupath.lib.plugins.parameters.ParameterList) List(java.util.List) ArrayList(java.util.ArrayList) PrintWriter(java.io.PrintWriter)

Aggregations

PathClass (qupath.lib.objects.classes.PathClass)66 ArrayList (java.util.ArrayList)42 PathObject (qupath.lib.objects.PathObject)34 List (java.util.List)29 Map (java.util.Map)25 IOException (java.io.IOException)21 Logger (org.slf4j.Logger)20 LoggerFactory (org.slf4j.LoggerFactory)20 Collections (java.util.Collections)17 Collectors (java.util.stream.Collectors)17 BufferedImage (java.awt.image.BufferedImage)16 LinkedHashMap (java.util.LinkedHashMap)16 ROI (qupath.lib.roi.interfaces.ROI)16 HashMap (java.util.HashMap)15 ImageData (qupath.lib.images.ImageData)15 PathClassFactory (qupath.lib.objects.classes.PathClassFactory)15 PathObjectHierarchy (qupath.lib.objects.hierarchy.PathObjectHierarchy)15 ParameterList (qupath.lib.plugins.parameters.ParameterList)15 Collection (java.util.Collection)14 TreeMap (java.util.TreeMap)11