I am trying to create image using http://www.hypeframework.org/ and processing.org. I want to create the image and store in a folder then display it on the web using java spark. The following are the steps that I started with.
Create maven project using NetBeans
Added processing.org, spark libraries in maven
Downloaded hype processing jar added to my libraries
My question is how do I create image with then save it to the webapp folder? I am relatively new to hype and processing drawing shapes stuff. The following are my code that I put together:
Right now this cimg.setup() in the main spark controller throws java.lang.NumberFormatException: For input string: "#BC7A38,#996A37,#968063,#AB977C,#997949,#AE9162,#DFC597,#CAB790" error.
I searched google, but can't find any lead. Any help on how I should accomplish my task is greatly appreciated. Thanks!
//-- spark controller -
public class Main {
public static void main(String[] args) {
get("/", new TemplateViewRoute() {
#Override
public ModelAndView handle(Request req, Response res) throws Exception {
HashMap model = new HashMap();
HypeProcessing cimg = new HypeProcessing();
cimg.setup();
model.put("template", "templates/form.vtl");
return new ModelAndView(model, "templates/layout.vtl");
}
}, new VelocityTemplateEngine());
}
}
//--- HypeProcessing class ----
public class HypeProcessing extends PApplet
{
HDrawablePool pool;
HColorPool colors;
#Override
public void setup()
{
int h = 300;
int w = 300;
//size(w, h);
//H.init(this).background(Integer.parseInt("#202020"));
//smooth();
colors = new HColorPool(Integer.parseInt("#BC7A38,#996A37,#968063,#AB977C,#997949,#AE9162,#DFC597,#CAB790"));
pool = new HDrawablePool(121);
pool.autoAddToStage()
.add(new HShape("svg1.svg"))
.add(new HShape("svg2.svg"))
.add(new HShape("svg3.svg"))
.add(new HShape("svg4.svg"))
.add(new HShape("svg5.svg"))
.add(new HShape("svg6.svg"))
.layout(
new HGridLayout()
.startX(50)
.startY(50)
.spacing(50,50)
.cols(11)
)
.onCreate(
new HCallback() {
#Override
public void run(Object obj) {
HShape d = (HShape) obj;
d
.enableStyle(false)
.strokeJoin(ROUND)
.strokeCap(ROUND)
.strokeWeight(1)
.stroke(Integer.parseInt("#000000"))
// .anchorAt(H.CENTER)
.rotate( (int)random(4) * 90 )
.size( 50 + ( (int)random(4) * 50 ) ) // 50, 100, 150, 200
;
d.randomColors(colors.fillOnly());
}
}
)
.requestAll();
saveImage(w,h);
noLoop();
// ...
}
#Override
public void draw()
{
//rect(10, 10, 80, 80);
H.drawStage();
// ...
}
public void saveImage(int width, int height)
{
//Helper c = new Helper();
String p = "webapp/images/";
String fn = p+"image_"+Helper.generateRandomNumber();
PGraphics img = createGraphics(width, height);
img.beginDraw();
boolean use3D = false;
float alpha = 1;
H.stage().paintAll(img, use3D, alpha);
img.endDraw();
img.save(fn);
}
}
Processing uses a custom color type. You can use web notation like #ff00ff, and under the hood Processing stores that as an integer, so you can even do things like:
int c = #ff00ff;
However, Java functions like Integer.parseInt() have no idea how to handle web notation. Java has no way of mapping a String like "#ff00ff" to an int value. This is why you're getting your error.
Even if Java did know how to map web notation to an int value, you're passing in multiple values within a single String, which doesn't make a ton of sense.
But the point is, you can only use web notation if you're using the Processing editor. If you're writing this in something other than the Processing editor, you'll have to use the color() function.
HColorPool(color(0, 255, 0), color(255, 0, 255), ...);
There is java code for the translation:-
java.awt.Color.decode("ff00ff").getRGB();
Its a bit obscure is what I use in JRubyArt
Related
How would I go about capturing an image for use in OpenCV from the standard camera module v2 plugged into a Raspberry Pi 3B? I've been trying to get high frame-rate video working, but using OpenCV's VideoCapture always gives me an empty Mat when I try to index device 0, and this and this both produced 1 frame per second or worse when I tried. I've also looked into spawning a raspivid process, but I don't see a way to get OpenCV's VideoCapture to read from the output of that process.
How would I get high FPS frame capture in Java? Is there a way I can get OpenCV to read from an OutputStream that I grab from another process?
EDIT: a simplified version of my code is below. I want to know how to populate the startRecording() function in this class
abstract class Main {
public static Mat currentCapture = null;
public static final double FOV_HEIGHT = 48.8;
public static final int WIDTH = 480;
public static final int HEIGHT = 384;
public static final int VIDEO_WIDTH = WIDTH * 2;
public static final int VIDEO_HEIGHT = HEIGHT * 2;
static {
System.loadLibrary(org.opencv.core.Core.NATIVE_LIBRARY_NAME);
}
public static void main(String[] args) {
client = new VisionClientTable("10.55.6.4", 5506);
new Thread(new VisionThread(VisionThread.Mode.VIDEO)).start();
new Thread(new VisionThread(VisionThread.Mode.TARGETING)).start();
}
private static class VisionThread implements Runnable {
private final Mode mode;
enum Mode {
VIDEO,
TARGETING
}
public VisionThread(Mode mode) {
this.mode = mode;
}
#Override
public void run() {
if (mode == Mode.TARGETING)
startTracking();
else if (mode == Mode.VIDEO)
startRecording();
}
}
public static void startTracking() {
/* this thread repeatedly captures currentCapture and processes it */
}
// this is where I need help
public static void startRecording() {
try {
VideoWriter video = new VideoWriter("/home/pi/vision/videos/video-" + Files.list(Paths.get("/home/pi/vision/captures")).count() + ".mp4", VideoWriter.fourcc('X', '2', '6', '4'), 30, new Size(VIDEO_WIDTH, VIDEO_HEIGHT), true);
VideoCapture capture = new VideoCapture(0);
capture.set(Videoio.CAP_PROP_FRAME_WIDTH, VIDEO_WIDTH);
capture.set(Videoio.CAP_PROP_FRAME_HEIGHT, VIDEO_HEIGHT);
Thread.sleep(2000);
while (true) {
long start = System.currentTimeMillis();
Mat mat = new Mat();
capture.read(mat);
if (!mat.empty()) { // mat is always empty
Mat downscaled = new Mat();
Imgproc.resize(mat, downscaled, new Size(WIDTH, HEIGHT), 0, 0, Imgproc.INTER_NEAREST);
currentCapture = downscaled;
}
video.write(mat);
long end = System.currentTimeMillis();
if (end - start < 1000 / 60)
Thread.sleep(1000 / 60 - (end - start));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void log(String text) {
System.out.println(text);
}
}
I feel like the best way to do this might be to set raspivid to output to a file, and somehow feed the output of it into OpenCV, but I'm not sure how to do this.
EDIT 2: So far, I have tried using Runtime.getRuntime().exec() to run a raspivid command that outputs to a file, which works, but then when I try to open that file with OpenCV, capture.isOpened() remains false, even as the program repeatedly tries to open the file.
not getting much idea about your code from your question.
following may help you.
http://bigdinotech.com/tutorials/beaglebone-black-tutorials/building-opencv-on-the-beaglebone-black-or-raspberry-pi/
I have added DragDetectListener and run doCommand in that. It gives true result but column doesn't gets freeze.
my code is :
natTable.addDragDetectListener(new DragDetectListener() {
#Override
public void dragDetected(DragDetectEvent paramDragDetectEvent) {
boolean b = natTable.doCommand(new FreezeColumnCommand(glazedListsGridLayer.getcompositeFreezeLayer(), 0));
}
});
Adding code of layer stack :
bodyDataLayer = new DataLayer(bodyDataProvider);
GlazedListsEventLayer<IzSearchResultRowData> glazedListsEventLayer = new GlazedListsEventLayer<IzSearchResultRowData>(bodyDataLayer, eventList);
bodyLayer = new DefaultBodyLayerStack(glazedListsEventLayer);
ColumnOverrideLabelAccumulator bodyLabelAccumulator = new ColumnOverrideLabelAccumulator(bodyDataLayer);
bodyDataLayer.setConfigLabelAccumulator(bodyLabelAccumulator);
// Column header layer
selectionLayer = bodyLayer.getSelectionLayer();
DataLayer columnHeaderDataLayer = new DefaultColumnHeaderDataLayer(bulkDataManager);
columnHeaderDataLayer.setRowHeightByPosition(0, 35);
final FreezeLayer freezeLayer = new FreezeLayer(selectionLayer);
final CompositeFreezeLayer compositeFreezeLayer = new CompositeFreezeLayer(
freezeLayer, bodyLayer.getViewportLayer(), selectionLayer);
ColumnHeaderLayer columnHeaderLayer = new ColumnHeaderLayer(columnHeaderDataLayer, compositeFreezeLayer, selectionLayer);
Another Thing :
I am getting position coordinates through selection layer. when i am running freeze command as
natTable.doCommand(new FreezeColumnCommand(glazedListsGridLayer.getSelectionLayer(), 0));
Its giving false result.
Hard to tell without seeing your layer stack. Maybe you have a more complicated layer composition and the command is lost on the way because of the index-position-transformation. Try to execute the command on the layer for which you provide the position coordinates.
natTable.addDragDetectListener(new DragDetectListener() {
#Override
public void dragDetected(DragDetectEvent paramDragDetectEvent) {
boolean b = glazedListsGridLayer.getcompositeFreezeLayer().doCommand(
new FreezeColumnCommand(glazedListsGridLayer.getcompositeFreezeLayer(), 0));
}
});
I'm using 32x32 and 64x64 (retina) for the same icon. When I tried using SKAnnotationView to display my icon, it loads up in double size (128x128). After I clear annotations and add again, the size returns to normal (64x64).
Please find the code below, I followed the sample project code:
SKAnnotation annotation = new SKAnnotation();
annotation.setUniqueID(-1);
annotation.setLocation(new SKCoordinate(longitude.doubleValue(), latitude.doubleValue()));
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
SKAnnotationView annotationView = new SKAnnotationView();
if (metrics.densityDpi < DisplayMetrics.DENSITY_HIGH) {
annotationView.setDrawableResourceId(R.drawable.ic_annotation);
annotation.setOffset(new SKScreenPoint(16, 16));
annotationView.setWidth(32);
annotationView.setHeight(32);
annotation.setImageSize(32);
} else {
annotationView.setDrawableResourceId(R.drawable.ic_annotation_retina);
annotation.setOffset(new SKScreenPoint(32, 32));
annotationView.setWidth(64);
annotationView.setHeight(64);
annotation.setImageSize(64);
}
annotation.setAnnotationView(annotationView);
mapView.addAnnotation(annotation, SKAnimationSettings.ANIMATION_NONE);
It might be too late , but you can try adding annotation at
#Override
public void onSurfaceCreated() {
}
callback.
This is my code :
public class OfflineMapFragment extends BaseFragment implements SKMapSurfaceListener {
private void addFilteredAnnotations(){
SKAnnotation annotation = new SKAnnotation();
annotation.setUniqueID(15);
annotation.setLocation(new SKCoordinate(Double.parseDouble(lat,long);
annotation.setMininumZoomLevel(5);
annotation.setOffset(new SKScreenPoint(128, 128));
SKAnnotationView annotationView = new SKAnnotationView();
annotationView.setDrawableResourceId(R.drawable.map_icon);
annotationView.setWidth(128);
annotationView.setHeight(128);
annotation.setAnnotationView(annotationView);
mapView.addAnnotation(annotation, SKAnimationSettings.ANIMATION_NONE);
}
#Override
public void onSurfaceCreated() {
addAnnotation();
}
}
My problem is annoying. My server side is generating 12 random numbers (double here).
My Client side received the correct data but nothing is displayed in my Chart. That worked fine with hardcoded data in the store but not with a REST call.
The transfer between my server and my client is that :
[{"key":"key0","value":0.47222548599297787},{"key":"key1","value":0.6009173797369691},{"key":"key2","value":0.13880104282435624},{"key":"key3","value":0.01804674319345545},{"key":"key4","value":0.5547733564202956},{"key":"key5","value":0.8229999661308851},{"key":"key6","value":0.8959346004391032},{"key":"key7","value":0.6848052288628435},{"key":"key8","value":0.10222856671111813},{"key":"key9","value":0.6931371931409103},{"key":"key10","value":0.2994297934549003},{"key":"key11","value":0.47566752196381334}]
Here my simple class used for my test. I am a newbie with GXT 3
public void onModuleLoad() {
final ListStore<JSOModel> store;
final ContentPanel panel = new FramedPanel();
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, "/ws/DocumentService/v1/test");
builder.setHeader("Accept", "application/json");
HttpProxy proxy = new HttpProxy(builder);
final Loader<ListLoadConfig, ListLoadResult<JSOModel>> loader = new ListLoader<ListLoadConfig, ListLoadResult<JSOModel>>(proxy, new DataReader<ListLoadResult<JSOModel>, String>() {
#Override
public ListLoadResult<JSOModel> read(Object loadConfig, String data) {
List<JSOModel> jsoModels = new ArrayList<JSOModel>();
JsArray<JSOModel> jsoModelJsArray = JSOModel.arrayFromJson(data);
if(jsoModelJsArray != null) {
for(int i = 0; i < jsoModelJsArray.length(); i++) {
jsoModels.add(jsoModelJsArray.get(i));
}
}
return new ListLoadResultBean<JSOModel>(jsoModels);
}
});
store = new ListStore<JSOModel>(new ModelKeyProvider<JSOModel>() {
#Override
public String getKey(JSOModel item) {
return item.get("key");
}
});
loader.addLoadHandler(new LoadResultListStoreBinding<ListLoadConfig, JSOModel, ListLoadResult<JSOModel>>(store) {
#Override
public void onLoad(LoadEvent<ListLoadConfig, ListLoadResult<JSOModel>> event) {
ListLoadResult<JSOModel> loaded = event.getLoadResult();
if(loaded.getData() == null) {
store.replaceAll(new ArrayList<JSOModel>());
} else {
store.replaceAll(loaded.getData());
}
}
});
Chart<JSOModel> chart = new Chart<JSOModel>();
chart.setStore(store);
chart.setShadowChart(true);
NumericAxis<JSOModel> axis = new NumericAxis<JSOModel>();
axis.setPosition(Chart.Position.LEFT);
axis.addField(new ValueProvider<JSOModel, Number>() {
#Override
public Number getValue(JSOModel JSOModel) {
return JSOModel.getNumber("value");
}
#Override
public void setValue(JSOModel JSOModel, Number number) {
}
#Override
public String getPath() {
return "key";
}
});
axis.setTitleConfig(new TextSprite("Number of hits"));
axis.setWidth(50);
axis.setMinimum(0);
axis.setMaximum(100);
chart.addAxis(axis);
PathSprite odd = new PathSprite();
odd.setOpacity(1);
odd.setFill(new Color("#dff"));
odd.setStroke(new Color("#aaa"));
odd.setStrokeWidth(0.5);
axis.setGridOddConfig(odd);
CategoryAxis<JSOModel, String> horizontalAxis = new CategoryAxis<JSOModel, String>();
horizontalAxis.setPosition(Chart.Position.BOTTOM);
horizontalAxis.setField(new ValueProvider<JSOModel, String>() {
#Override
public String getValue(JSOModel JSOModel) {
return JSOModel.get("key");
}
#Override
public void setValue(JSOModel JSOModel, String s) {
}
#Override
public String getPath() {
return "key";
}
});
horizontalAxis.setTitleConfig(new TextSprite("month of year"));
chart.addAxis(horizontalAxis);
LineSeries<JSOModel> column = new LineSeries<JSOModel>();
column.setYAxisPosition(Chart.Position.LEFT);
column.setStroke(new RGB(148,174,10));
column.setHighlighting(true);
chart.addSeries(column);
axis.addField(column.getYField());
chart.addSeries(column);
chart.setHeight(100);
chart.setWidth(100);
Button b = new Button("ha");
b.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent clickEvent) {
loader.load();
}
});
RootPanel.get().add(b);
panel.setCollapsible(true);
panel.setHeadingText("Column Chart");
panel.setPixelSize(620, 500);
panel.setBodyBorder(true);
VerticalLayoutContainer layout = new VerticalLayoutContainer();
panel.add(layout);
chart.setLayoutData(new VerticalLayoutContainer.VerticalLayoutData(1,1));
layout.add(chart);
chart.setBackground(new Color("#dff"));
RootPanel.get().add(panel);
There are two ways to wire the chart into a store. One is to simply specify that the chart is using a store via setStore, as you have done:
chart.setStore(store);
When you do this, you must also inform the chart when it must redraw everything - you must call:
chart.redrawChart();
This call must be made shortly after the load is completed - consider doing it at the end of onLoad.
Why is this required? In some cases, developers want to make many changes to the store, one at a time, and if the chart automatically updated after each change, that would spawn many slow changes to the data model, and could end up looking strange. In a case like this, you would only call redrawChart() after all changes were complete.
There is another option however - instead of calling setStore, you can call bindStore, and ask the Chart to automatically update whenever any change occurs to the chart:
chart.bindStore(store);
In your case, this is likely the correct answer.
I'm using the GWT google maps V3 API and I need to display custom shapes over the map.
For simple elements I used Polygon, Circle and InfoWidnow classes, but I want to display some other widgets like button or custom panels.
Is there any way to do that using OverlayView class ? I tried a simple solution: an AbsolutePanel that contains the MapWidget and my custom widgets, placed on top, but I would like to use the gwt google maps classes as much as I can. I've read the documentation and also searched for an answer but I could't figure it out so a code example would be great.
Thanx!
Just make use of standard GWT API alongside with your maps V3 API. They will interconnect well enough.
I found what i needed here (the javascript v3 api):
https://developers.google.com/maps/documentation/javascript/overlays#CustomOverlays
the method names and classes are very similar so it isn't so difficult to figure out how the GWT classes should be used (like OverlayView).
Here is an example with custom widgets (containing SVG elements and animation) rendered on the map:
private class TargettingOverlay extends OverlayView {
protected Element div ;
protected PanelWrapper panelWrapper;
private TargettingEffect targetEffect;
TargettingOverlay(){
targetEffect = new TargettingEffect();
targetEffect.setLinedDimension(10500);
targetEffect.setLinesOffset(-5000);
}
void positionTarget(LatLng loc, boolean withoutLines){
if (targetEffect == null )
return;
if (loc == null) {
targetEffect.setElementsVisible(false);
return;
}
targetEffect.setElementsVisible(true);
Point p = null;
Point sw = null;
Point ne = null;
LatLng locSW = (LatLng)this.getMap().getBounds().getSouthWest();
LatLng locNE = (LatLng)this.getMap().getBounds().getNorthEast();
//
p = (Point)getProjection().fromLatLngToDivPixel(loc);
sw = (Point)getProjection().fromLatLngToDivPixel(locSW);
ne = (Point)getProjection().fromLatLngToDivPixel(locNE);
targetEffect.setWithoutLinles(withoutLines);
targetEffect.target((int)ne.getY(), (int)p.getY(), (int)sw.getX(), (int)p.getX());
}
#Override
public void draw() {
Point ne = (Point)getProjection().fromLatLngToDivPixel((LatLng)
this.getMap().getBounds().getNorthEast());
Point sw = (Point)getProjection().fromLatLngToDivPixel((LatLng)
this.getMap().getBounds().getSouthWest());
div.getStyle().setTop(ne.getY(), Unit.PX);
div.getStyle().setLeft(sw.getX(), Unit.PX);
}
#Override
public void onAdd() {
div = DOM.createDiv();
getPanes().getOverlayLayer().appendChild(div);
panelWrapper = new PanelWrapper(div);
panelWrapper.attach();
targetEffect.setContainer(panelWrapper);
}
#Override
public void onRemove() {
div.removeFromParent();
panelWrapper.removeFromParent();
div = null;
panelWrapper = null;
}
}