Class VisionCameraView<T>
- Type Parameters:
T- the analyzer's result type
- All Implemented Interfaces:
Animation, Editable, StyleListener, AutoCloseable, Iterable<Component>
A live camera preview that runs an analyzer over its frames.
This is the whole camera-to-analyzer pipeline as one component: it opens
the camera when it is shown, streams frames into the analyzer with
keep-only-the-newest backpressure, delivers results on the EDT, and
releases the camera when the form is left. Add it to a form and implement
the listener; there is no session, frame listener, or
VisionImage conversion to write.
FaceDetector detector = new FaceDetector();
VisionCameraView<Face[]> view = new VisionCameraView<Face[]>(detector);
view.setFacing(CameraFacing.FRONT);
view.setListener(new VisionPipelineListener<Face[]>() {
public void result(Face[] faces, VisionImage source) {
countLabel.setText(faces.length + " face(s)");
}
public void error(Throwable error) {
Log.e(error);
}
});
Form form = new Form("Faces", new BorderLayout());
form.add(BorderLayout.CENTER, view);
form.add(BorderLayout.SOUTH, countLabel);
form.show();
The analyzer is supplied by the caller rather than named by a feature constant, which is deliberate: the build pipeline decides which native vision dependency to package from the analyzer classes an application references, so constructing the analyzer in application code is what keeps a face-detection app from also carrying the barcode and pose models.
The preview is a native view. Codename One components cannot be painted
over it on every platform -- iOS renders native peers behind the Codename
One layer, Android renders them in front -- so put a scanner's reticle,
hints, and buttons around the preview rather than on top of it. Result
geometry such as Face.getBounds() can still be drawn in a component
beside the preview using VisionRect.toBounds(com.codename1.ui.Component).
One camera session may be open at a time, so a second view (or a
Capture call) while this one is showing
reports an error to the listener instead of stealing the hardware.
-
Field Summary
Fields inherited from class Component
BASELINE, BOTTOM, BRB_CENTER_OFFSET, BRB_CONSTANT_ASCENT, BRB_CONSTANT_DESCENT, BRB_OTHER, CENTER, CROSSHAIR_CURSOR, DEFAULT_CURSOR, DRAG_REGION_IMMEDIATELY_DRAG_X, DRAG_REGION_IMMEDIATELY_DRAG_XY, DRAG_REGION_IMMEDIATELY_DRAG_Y, DRAG_REGION_LIKELY_DRAG_X, DRAG_REGION_LIKELY_DRAG_XY, DRAG_REGION_LIKELY_DRAG_Y, DRAG_REGION_NOT_DRAGGABLE, DRAG_REGION_POSSIBLE_DRAG_X, DRAG_REGION_POSSIBLE_DRAG_XY, DRAG_REGION_POSSIBLE_DRAG_Y, E_RESIZE_CURSOR, HAND_CURSOR, LEFT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NW_RESIZE_CURSOR, RIGHT, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, TOP, W_RESIZE_CURSOR, WAIT_CURSOR -
Constructor Summary
ConstructorsConstructorDescriptionVisionCameraView(VisionAnalyzer<T> analyzer) Creates a view that runsanalyzerover the back camera. -
Method Summary
Modifier and TypeMethodDescriptionvoidclose()Releases the camera and the analyzer.protected voidReleases the camera when the view stops being shown.intThe open camera session, for torch, zoom, focus, or a still capture.protected voidOpens the camera when the view becomes part of a shown form.booleanbooleanWhether the current platform can open a camera and run this view's analyzer.voidsetFacing(CameraFacing value) Selects which camera to open.voidsetListener(VisionPipelineListener<T> value) Installs the callback for analysis results and recoverable failures.voidsetMaxFps(int value) Caps how many frames per second reach the analyzer.voidsetScaleType(ScaleType value) How the preview is fitted into this component's bounds.voidsetTorchEnabled(boolean on) Turns the torch on or off, when the open camera has one.voidstart()Opens the camera and starts analyzing.voidstop()Stops analyzing and releases the camera, leaving the analyzer usable.Methods inherited from class Container
add, add, add, add, add, add, addAll, addComponent, addComponent, addComponent, addComponent, animateHierarchy, animateHierarchyAndWait, animateHierarchyFade, animateHierarchyFadeAndWait, animateLayout, animateLayoutAndWait, animateLayoutFade, animateLayoutFadeAndWait, animateUnlayout, animateUnlayoutAndWait, applyRTL, calcPreferredSize, cancelRepaints, clearClientProperties, constrainHeightWhenScrollable, constrainWidthWhenScrollable, contains, createAnimateHierarchy, createAnimateHierarchyFade, createAnimateLayout, createAnimateLayoutFade, createAnimateLayoutFadeAndWait, createAnimateMotion, createAnimateUnlayout, createReplaceTransition, dragInitiated, drop, encloseIn, encloseIn, findDropTargetAt, findFirstFocusable, fireClicked, flushReplace, forceRevalidate, getBottomGap, getChildrenAsList, getClosestComponentTo, getComponentAt, getComponentAt, getComponentCount, getComponentIndex, getGridPosX, getGridPosY, getLayout, getLayoutHeight, getLayoutWidth, getLeadComponent, getLeadParent, getResponderAt, getSafeAreaRoot, getScrollIncrement, getSideGap, getUIManager, initLaf, invalidate, isEnabled, isSafeArea, isSafeAreaRoot, isScrollableX, isScrollableY, isSelectableInteraction, isSurface, iterator, iterator, keyPressed, keyReleased, layoutContainer, morph, morphAndWait, paint, paintComponentBackground, paintGlass, paramString, pointerPressed, refreshTheme, removeAll, removeComponent, replace, replace, replaceAndWait, replaceAndWait, replaceAndWait, revalidate, revalidateLater, revalidateWithAnimationSafety, scrollComponentToVisible, setCellRenderer, setEnabled, setLayout, setLeadComponent, setSafeArea, setSafeAreaRoot, setScrollable, setScrollableX, setScrollableY, setScrollIncrement, setShouldCalcPreferredSize, setShouldLayout, setUIManager, updateTabIndicesMethods inherited from class Component
accessibilityChanged, accessibilityChanged, addContextMenuListener, addDragFinishedListener, addDragOverListener, addDropListener, addFocusListener, addLongPressListener, addMouseWheelListener, addPointerDraggedListener, addPointerPressedListener, addPointerReleasedListener, addPullToRefresh, addScrollListener, addStateChangeListener, addStylusListener, animate, announceForAccessibility, bindProperty, blocksSideSwipe, calcScrollSize, consumesRawTextInput, contains, containsOrOwns, createStyleAnimation, deinitializeCustomStyle, dragEnter, dragExit, dragFinished, draggingOver, drawDraggedImage, focusGained, focusLost, getAbsoluteX, getAbsoluteY, getAccessibilityNode, getAccessibilityText, getAllStyles, getAnimationManager, getBaseline, getBaselineResizeBehavior, getBindablePropertyNames, getBindablePropertyTypes, getBorder, getBoundPropertyValue, getBounds, getBounds, getClientProperty, getCloudBoundProperty, getCloudDestinationProperty, getComponentForm, getComponentState, getCursor, getDefaultDragTransparency, getDirtyRegion, getDisabledStyle, getDraggedx, getDraggedy, getDragImage, getDragRegionStatus, getDragSpeed, getDragTransparency, getEditingDelegate, getHeight, getInlineAllStyles, getInlineDisabledStyles, getInlinePressedStyles, getInlineSelectedStyles, getInlineStylesTheme, getInlineUnselectedStyles, getInnerHeight, getInnerPreferredH, getInnerPreferredW, getInnerWidth, getInnerX, getInnerY, getLabelForComponent, getName, getNativeOverlay, getNextFocusDown, getNextFocusLeft, getNextFocusRight, getNextFocusUp, getOuterHeight, getOuterPreferredH, getOuterPreferredW, getOuterWidth, getOuterX, getOuterY, getOwner, getParent, getPreferredH, getPreferredSize, getPreferredSizeStr, getPreferredTabIndex, getPreferredW, getPressedStyle, getPropertyNames, getPropertyTypeNames, getPropertyTypes, getPropertyValue, getSameHeight, getSameWidth, getScrollable, getScrollAnimationSpeed, getScrollDimension, getScrollOpacity, getScrollOpacityChangeSpeed, getScrollX, getScrollY, getSelectCommandText, getSelectedRect, getSelectedStyle, getSemantics, getStyle, getTabIndex, getTensileLength, getTextSelectionSupport, getTooltip, getUIID, getUnselectedStyle, getVisibleBounds, getVisibleBounds, getWidth, getX, getY, growShrink, handlesInput, hasFixedPreferredSize, hasFocus, hideNativeOverlay, initCustomStyle, initDisabledStyle, initPressedStyle, initSelectedStyle, initUnselectedStyle, installDefaultPainter, isAlwaysTensile, isBlockLead, isCellRenderer, isChildOf, isDragActivated, isDragAndDropOperation, isDraggable, isDragRegion, isDropTarget, isEditable, isEditing, isFlatten, isFocusable, isGrabsPointerEvents, isHidden, isHidden, isHideInLandscape, isHideInPortrait, isHScrollThumbGrabbed, isHScrollThumbHover, isIgnorePointerEvents, isInClippingRegion, isInitialized, isOpaque, isOwnedBy, isPinchBlocksDragAndDrop, isRippleEffect, isRTL, isScrollable, isScrollVisible, isSetCursorSupported, isSmoothScrolling, isSnapToGrid, isStickyDrag, isTactileTouch, isTactileTouch, isTensileDragEnabled, isTraversable, isVisible, isVScrollThumbGrabbed, isVScrollThumbHover, keyRepeated, laidOut, longKeyPress, longPointerPress, onScrollX, onScrollY, onSetFocusable, paintBackground, paintBackgrounds, paintBorder, paintBorderBackground, paintComponent, paintComponent, paintIntersectingComponentsAbove, paintLock, paintLockRelease, paintRippleOverlay, paintScrollbars, paintScrollbarX, paintScrollbarY, paintShadows, parsePreferredSize, pinch, pinch, pinchReleased, pointerDragged, pointerDragged, pointerHover, pointerHoverPressed, pointerHoverReleased, pointerPressed, pointerReleased, pointerReleased, putClientProperty, refreshTheme, refreshTheme, remove, removeContextMenuListener, removeDragFinishedListener, removeDragOverListener, removeDropListener, removeFocusListener, removeLongPressListener, removeMouseWheelListener, removePointerDraggedListener, removePointerPressedListener, removePointerReleasedListener, removeScrollListener, removeStateChangeListener, removeStylusListener, repaint, repaint, requestFocus, resetFocusable, respondsToPointerEvents, rotation, scrollRectToVisible, scrollRectToVisible, setAccessibilityText, setAlwaysTensile, setBlockLead, setBoundPropertyValue, setCloudBoundProperty, setCloudDestinationProperty, setComponentState, setCursor, setDefaultDragTransparency, setDirtyRegion, setDisabledStyle, setDraggable, setDragTransparency, setDropTarget, setEditingDelegate, setFlatten, setFocus, setFocusable, setGrabsPointerEvents, setHandlesInput, setHeight, setHidden, setHidden, setHideInLandscape, setHideInPortrait, setHorizontalScrollBounds, setIgnorePointerEvents, setInitialized, setInlineAllStyles, setInlineDisabledStyles, setInlinePressedStyles, setInlineSelectedStyles, setInlineStylesTheme, setInlineUnselectedStyles, setIsScrollVisible, setLabelForComponent, setName, setNextFocusDown, setNextFocusLeft, setNextFocusRight, setNextFocusUp, setOpaque, setOwner, setPinchBlocksDragAndDrop, setPreferredH, setPreferredSize, setPreferredSizeStr, setPreferredTabIndex, setPreferredW, setPressedStyle, setPropertyValue, setPullToRefresh, setRippleEffect, setRTL, setSameHeight, setSameSize, setSameWidth, setScrollAnimationSpeed, setScrollOpacityChangeSpeed, setScrollSize, setScrollVisible, setScrollX, setScrollY, setSelectCommandText, setSelectedStyle, setSize, setSmoothScrolling, setSnapToGrid, setTabIndex, setTactileTouch, setTensileDragEnabled, setTensileLength, setTooltip, setTraversable, setUIID, setUIID, setUIIDFinal, setUnselectedStyle, setVerticalScrollBounds, setVisible, setWidth, setX, setY, shouldBlockSideSwipe, shouldBlockSideSwipeLeft, shouldBlockSideSwipeRight, shouldRenderComponentSelection, showNativeOverlay, startEditingAsync, stopEditing, stripMarginAndPadding, styleChanged, toImage, toString, unbindProperty, updateNativeOverlay, visibleBoundsContains
-
Constructor Details
-
VisionCameraView
Creates a view that runs
analyzerover the back camera.The view borrows the analyzer: leaving the form releases the camera but keeps the analyzer usable, and
close()releases it for good.- Parameters:
analyzer- the reusable analyzer to run over each frame- Throws:
NullPointerException- ifanalyzerisnull
-
-
Method Details
-
isSupported
public boolean isSupported()Whether the current platform can open a camera and run this view's analyzer. Check this before showing the view: a target without either piece reports failures through the listener rather than throwing.- Returns:
truewhen both the camera and the analyzer are available
-
setFacing
Selects which camera to open. Takes effect the next time the view is shown; the default is
CameraFacing.BACK.A front camera's preview is requested mirrored, the way a selfie view behaves. The simulator honors that; the iOS and Android previews do not mirror yet. Note also that a device without the requested camera falls back to whatever it has, and the mirroring follows the camera that actually opened rather than the one asked for.
- Parameters:
value- the camera to prefer, ornullfor the back camera
-
getFacing
- Returns:
- the camera this view opens
-
setMaxFps
public void setMaxFps(int value) Caps how many frames per second reach the analyzer. Frames arriving while an analysis is in flight are dropped in favor of the newest one regardless of this value, so the cap mainly saves the camera the work of producing frames nothing will read. The default is 10.- Parameters:
value- frames per second, or0for uncapped
-
getMaxFps
public int getMaxFps()- Returns:
- the frame rate cap, or
0when uncapped
-
setScaleType
How the preview is fitted into this component's bounds. The default is
ScaleType.CROP, which fills the view the way a camera app does.The simulator honors every mode. The iOS and Android previews render fixed at fill-and-crop today, because neither port implements the scaling hook yet, so a non-default mode is a request those targets currently ignore rather than a promise.
- Parameters:
value- the scaling to apply, ornullfor the default
-
getScaleType
- Returns:
- how the preview is fitted into this component's bounds
-
setListener
Installs the callback for analysis results and recoverable failures. Both are delivered on the EDT.- Parameters:
value- the listener, ornullto stop receiving results
-
getListener
- Returns:
- the installed result listener, or
null
-
getSession
The open camera session, for torch, zoom, focus, or a still capture.- Returns:
- the session while the view is showing, or
null
-
setTorchEnabled
public void setTorchEnabled(boolean on) Turns the torch on or off, when the open camera has one. A camera without a flash ignores this.- Parameters:
on- whether the torch should be lit
-
isRunning
public boolean isRunning()- Returns:
truewhile the camera is open and frames are flowing
-
start
public void start()Opens the camera and starts analyzing. Called automatically when the view is shown; calling it again while running does nothing. -
stop
public void stop()Stops analyzing and releases the camera, leaving the analyzer usable. Called automatically when the view stops being shown. -
close
public void close()Releases the camera and the analyzer. Use this when the view will not be shown again; simply navigating to another form already releases the camera. Calling it more than once has no effect.- Specified by:
closein interfaceAutoCloseable
-
initComponent
protected void initComponent()Opens the camera when the view becomes part of a shown form.- Overrides:
initComponentin classComponent
-
deinitialize
protected void deinitialize()Releases the camera when the view stops being shown.- Overrides:
deinitializein classComponent
-