Search in sources :

Example 1 with FastAccess

use of org.ddogleg.struct.FastAccess in project BoofCV by lessthanoptimal.

the class SerializeFieldsYamlBase method serialize.

/**
 * Serializes the specified config. If a 'canonical' reference is provided then only what is not identical
 * in value to the canonical is serialized.
 *
 * @param config Object that is to be serialized
 * @param canonical Canonical object.
 */
public Map<String, Object> serialize(Object config, @Nullable Object canonical) {
    Map<String, Object> state = new HashMap<>();
    Class type = config.getClass();
    Field[] fields = type.getFields();
    // Get a list of active fields, if a list is specified by the configuration
    List<String> active = new ArrayList<>();
    if (config instanceof Configuration) {
        active = ((Configuration) config).serializeActiveFields();
    }
    for (Field f : fields) {
        if (!(active.isEmpty() || active.contains(f.getName())))
            continue;
        try {
            if (f.getType().isEnum() || f.getType().isPrimitive() || f.getType().getName().equals("java.lang.String")) {
                try {
                    // Only add if they are not identical
                    Object targetValue = f.get(config);
                    Object canonicalValue = canonical == null ? null : f.get(canonical);
                    if (canonicalValue == null && targetValue == null)
                        continue;
                    if (targetValue == null || !targetValue.equals(canonicalValue))
                        state.put(f.getName(), f.getType().isEnum() ? ((Enum<?>) targetValue).name() : targetValue);
                } catch (RuntimeException e) {
                    errorHandler.handle(ErrorType.MISC, "class=" + type.getSimpleName() + " field=" + f.getName(), e);
                }
                continue;
            }
            // FastArray are a special case. Serialize each element in the list
            if (FastAccess.class.isAssignableFrom(f.getType())) {
                FastAccess<?> list = (FastAccess<?>) f.get(config);
                // See if the lists are identical. If they are then skip them
                escape: if (canonical != null) {
                    FastAccess<?> listCanon = (FastAccess<?>) f.get(canonical);
                    if (list.size() != listCanon.size())
                        break escape;
                    if (list.isEmpty())
                        continue;
                    for (int i = 0; i < list.size(); i++) {
                        if (!list.get(i).equals(listCanon.get(i)))
                            break escape;
                    }
                    continue;
                }
                // Encode the list. Basic types are just copied. Everything else is serialized.
                Class<?> itemType = list.type;
                boolean basic = itemType.isEnum() || itemType.isPrimitive() || itemType.getName().equals("java.lang.String");
                // Create the canonical if possible
                Object canonicalOfData = null;
                if (canonical != null && !basic) {
                    try {
                        canonicalOfData = list.type.getConstructor().newInstance();
                    } catch (Exception e) {
                        errorHandler.handle(ErrorType.MISC, "Failed to create instance of '" + list.type.getSimpleName() + "'", null);
                    }
                }
                List<Object> serializedList = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    Object value = list.get(i);
                    if (basic) {
                        serializedList.add(itemType.isEnum() ? ((Enum<?>) value).name() : value);
                    } else {
                        serializedList.add(serialize(value, canonicalOfData));
                    }
                }
                state.put(f.getName(), serializedList);
                continue;
            }
            if (List.class.isAssignableFrom(f.getType())) {
                errorHandler.handle(ErrorType.UNSUPPORTED, "Can't serialize lists. Use FastArray instead " + "since it specifies the item type. name=" + f.getName(), null);
                continue;
            }
            // handle primitive arrays
            if (f.getType().isArray()) {
                state.put(f.getName(), f.get(config));
                continue;
            }
            try {
                // All Configuration must have setTo()
                // We don't check to see if implements Configuration to allow objects outside of BoofCV
                // to work.
                type.getMethod("setTo", type);
            } catch (NoSuchMethodException e) {
                // This is intentionally annoying as a custom class specific serialization solution
                // needs to be created. For now, it will complain and skip
                errorHandler.handle(ErrorType.UNSUPPORTED, "Referenced object which is not enum, primitive, " + "or a valid class. class='" + type.getSimpleName() + "' field_name='" + f.getName() + "'", null);
                continue;
            }
            Map<String, Object> result = canonical != null ? serialize(f.get(config), f.get(canonical)) : serialize(f.get(config), null);
            // If everything is identical then the returned object will be empty
            if (!result.isEmpty())
                state.put(f.getName(), result);
        } catch (IllegalAccessException e) {
            errorHandler.handle(ErrorType.REFLECTION, String.format("IllegalAccess. class='%s' field='%s'", type.getSimpleName(), f.getName()), new RuntimeException(e));
        }
    }
    return state;
}
Also used : Configuration(boofcv.struct.Configuration) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) FastAccess(org.ddogleg.struct.FastAccess) InvocationTargetException(java.lang.reflect.InvocationTargetException) Field(java.lang.reflect.Field)

Example 2 with FastAccess

use of org.ddogleg.struct.FastAccess in project BoofCV by lessthanoptimal.

the class DetectECoCheckApp method processImage.

@Override
public void processImage(int sourceID, long frameID, BufferedImage buffered, ImageBase input) {
    original = ConvertBufferedImage.checkCopy(buffered, original);
    GrayF32 gray = (GrayF32) input;
    double processingTime;
    synchronized (lockAlgorithm) {
        long time0 = System.nanoTime();
        detector.process(gray);
        long time1 = System.nanoTime();
        // milliseconds
        processingTime = (time1 - time0) * 1e-6;
        FastAccess<ECoCheckFound> found = detector.getFound();
        synchronized (lockVisualize) {
            visualizeUtils.update(detector);
            // Copy found chessboard patterns
            this.foundPatterns.resetResize(found.size);
            for (int i = 0; i < found.size; i++) {
                this.foundPatterns.get(i).setTo(found.get(i));
                // Sort so that they have some sane order when visualized
                Collections.sort(foundPatterns.get(i).corners.toList(), Comparator.comparingInt(a -> a.index));
            }
        }
        System.out.println("found.size=" + found.size);
        for (int i = 0; i < found.size; i++) {
            ECoCheckFound c = found.get(i);
            if (!controlPanel.showAnonymous.value && c.markerID < 0)
                continue;
            System.out.println("[" + i + "]");
            System.out.println("  marker=" + c.markerID);
            System.out.println("  rows=" + c.squareRows);
            System.out.println("  cols=" + c.squareCols);
            System.out.println("  decoded=" + c.decodedCells.size);
        }
    }
    SwingUtilities.invokeLater(() -> {
        controlPanel.setImageSize(original.getWidth(), original.getHeight());
        controlPanel.setProcessingTimeMS(processingTime);
        imagePanel.setBufferedImageNoChange(original);
        imagePanel.repaint();
    });
}
Also used : Point2D_F64(georegression.struct.point.Point2D_F64) GrayF32(boofcv.struct.image.GrayF32) ShapeVisualizePanel(boofcv.demonstrations.shapes.ShapeVisualizePanel) KeyAdapter(java.awt.event.KeyAdapter) ImageBase(boofcv.struct.image.ImageBase) MAX_ZOOM(boofcv.gui.BoofSwingUtil.MAX_ZOOM) ArrayList(java.util.ArrayList) VisualizeChessboardXCornerUtils(boofcv.demonstrations.calibration.VisualizeChessboardXCornerUtils) StandardAlgConfigPanel(boofcv.gui.StandardAlgConfigPanel) FactoryFiducial(boofcv.factory.fiducial.FactoryFiducial) SimpleImageSequence(boofcv.io.image.SimpleImageSequence) BoofMiscOps(boofcv.misc.BoofMiscOps) MouseAdapter(java.awt.event.MouseAdapter) TitledBorder(javax.swing.border.TitledBorder) ChessboardCorner(boofcv.alg.feature.detect.chess.ChessboardCorner) UtilAngle(georegression.metric.UtilAngle) UtilIO(boofcv.io.UtilIO) ImageType(boofcv.struct.image.ImageType) BufferedImage(java.awt.image.BufferedImage) UtilCalibrationGui(boofcv.gui.calibration.UtilCalibrationGui) ConfigECoCheckDetector(boofcv.abst.fiducial.calib.ConfigECoCheckDetector) DogArray(org.ddogleg.struct.DogArray) ECoCheckDetector(boofcv.alg.fiducial.calib.ecocheck.ECoCheckDetector) PathLabel(boofcv.io.PathLabel) ConvertBufferedImage(boofcv.io.image.ConvertBufferedImage) KeyEvent(java.awt.event.KeyEvent) AffineTransform(java.awt.geom.AffineTransform) MouseEvent(java.awt.event.MouseEvent) FastAccess(org.ddogleg.struct.FastAccess) java.awt(java.awt) List(java.util.List) JSpinnerNumber(boofcv.gui.controls.JSpinnerNumber) DetectBlackShapePanel(boofcv.demonstrations.shapes.DetectBlackShapePanel) MIN_ZOOM(boofcv.gui.BoofSwingUtil.MIN_ZOOM) BoofSwingUtil(boofcv.gui.BoofSwingUtil) JCheckBoxValue(boofcv.gui.controls.JCheckBoxValue) ConfigECoCheckMarkers(boofcv.abst.fiducial.calib.ConfigECoCheckMarkers) Comparator(java.util.Comparator) DemonstrationBase(boofcv.gui.DemonstrationBase) Collections(java.util.Collections) ECoCheckFound(boofcv.alg.fiducial.calib.ecocheck.ECoCheckFound) javax.swing(javax.swing) GrayF32(boofcv.struct.image.GrayF32) ECoCheckFound(boofcv.alg.fiducial.calib.ecocheck.ECoCheckFound)

Aggregations

ArrayList (java.util.ArrayList)2 FastAccess (org.ddogleg.struct.FastAccess)2 ConfigECoCheckDetector (boofcv.abst.fiducial.calib.ConfigECoCheckDetector)1 ConfigECoCheckMarkers (boofcv.abst.fiducial.calib.ConfigECoCheckMarkers)1 ChessboardCorner (boofcv.alg.feature.detect.chess.ChessboardCorner)1 ECoCheckDetector (boofcv.alg.fiducial.calib.ecocheck.ECoCheckDetector)1 ECoCheckFound (boofcv.alg.fiducial.calib.ecocheck.ECoCheckFound)1 VisualizeChessboardXCornerUtils (boofcv.demonstrations.calibration.VisualizeChessboardXCornerUtils)1 DetectBlackShapePanel (boofcv.demonstrations.shapes.DetectBlackShapePanel)1 ShapeVisualizePanel (boofcv.demonstrations.shapes.ShapeVisualizePanel)1 FactoryFiducial (boofcv.factory.fiducial.FactoryFiducial)1 BoofSwingUtil (boofcv.gui.BoofSwingUtil)1 MAX_ZOOM (boofcv.gui.BoofSwingUtil.MAX_ZOOM)1 MIN_ZOOM (boofcv.gui.BoofSwingUtil.MIN_ZOOM)1 DemonstrationBase (boofcv.gui.DemonstrationBase)1 StandardAlgConfigPanel (boofcv.gui.StandardAlgConfigPanel)1 UtilCalibrationGui (boofcv.gui.calibration.UtilCalibrationGui)1 JCheckBoxValue (boofcv.gui.controls.JCheckBoxValue)1 JSpinnerNumber (boofcv.gui.controls.JSpinnerNumber)1 PathLabel (boofcv.io.PathLabel)1