I am writing ESRI geometry compression algorithm in JAVA, I am using this link.
Using instructions mentioned in provided link, this is my current code:
public static void main(String[] args) {
String dirPoints = "-118.356654545455,34.1146;-118.356436363636,34.1143272727273;-118.356418181818,34.1142363636364;-118.356490909091,34.1137636363636";
String compressedGeometry = "";
double xPointPrev = 0.0;
double yPointPrev = 0.0;
int coefficient = 55000;
String coefficient_32 = Integer.toString(coefficient, 32);
compressedGeometry = coefficient_32 + compressedGeometry;
String[] path_XY = dirPoints.split(";");
for (int i = 0, leni = path_XY.length; i < leni; i++) {
String[] xy = path_XY[i].split(",");
double pointX = Double.parseDouble(xy[0].trim());
double pointY = Double.parseDouble(xy[1].trim());
int xDifference = (int) Math.round(coefficient * (pointX - xPointPrev));
int yDifference = (int) Math.round(coefficient * (pointY - yPointPrev));
String xDifference_32 = Integer.toString(xDifference, 32);
compressedGeometry += xDifference_32;
String yDifference_32 = Integer.toString(yDifference, 32);
compressedGeometry += yDifference_32;
xPointPrev = pointX;
yPointPrev = pointY;
}
System.out.println(compressedGeometry);
}
Expected output: "+1lmo-66l1f+1p8af+c-f+1-5-4-q"
But I am getting this: "1lmo-66l1g1p8afc-f1-5-4-q"
What am I missing? Any help is highly appreciated.
Thanks,
According to Integer.toString()
"If the first argument is not negative, no sign character appears in the result."
Therefore I think you need to add the "+".
(And I think the f-g there is their typo).
Related
Given a StyledText, initializied with SWT.MULTI and SWT.WRAP, I need to calculate the appropriate height hint based on the appropriate lines count for the content.
In this image you can see how the editor is resized when the content changes
The code that calculates the lines to display is the following
private int calcRealLinesCount() {
final int componentWidth = styledText.getSize().x;
final int dumbLinesCount = styledText.getLineCount();
int realLinesCount = 0;
for (int i = 0; i < dumbLinesCount; i++) {
final String lineText = styledText.getLine(i);
final Point lineTextExtent = styledTextGc.textExtent(lineText);
final double lines = lineTextExtent.x / (double) componentWidth;
realLinesCount += (int) Math.max(1D, Math.ceil(lines));
}
return Math.max(dumbLinesCount, realLinesCount);
}
The lines count is then used to get the appropriate height
((GridData) layoutData).heightHint = realLinesCount * fontHeight;
However, this code does not consider word wraps, and I cannot think of a way to do it.
Any ideas? Could I do this in a different way?
Thanks to Greg for the JFaceTextUtil#computeLineHeight hint.
I could not use that directly, but I've at least learned how JFace does what I need.
The following is what I'm using now to get a StyledText's line height:
private int computeRealLineHeight(final int lineIndex) {
final int startOffset = styledText.getOffsetAtLine(lineIndex);
final String lineText = styledText.getLine(lineIndex);
if (lineText.isEmpty()) {
return styledText.getLineHeight(startOffset);
}
final int endOffset = startOffset + lineText.length() - 1;
final Rectangle textBounds = styledText.getTextBounds(startOffset, endOffset);
return textBounds.height;
}
I've had a lot of experience with Java, and have already written my own utilities for processing imagery. I realise that there are many tutorials out there for Python, but I'm much more inclined to use Java as I would like to integrate some of the facilities of OpenCV 4.1 with my existing Java code.
One of my experiments is to try and obtain the masks of objects identified ion images using the coco dataset
// Give the textGraph and weight files for the model
private static final String TEXT_GRAPH = "models/mask_rcnn_inception_v2_coco_2018_01_28.pbtxt";
private static final String MODEL_WEIGHTS = "models/mask_rcnn_inception_v2_coco_2018_01_28/frozen_inference_graph.pb";
private static final String CLASSES_FILE = "models/mscoco_labels.names";
TextFileConsumer consumer = new TextFileConsumer();
File textFile = new File(CLASSES_FILE);
if (textFile.exists()){
BufferedReader fr1 = new BufferedReader(new FileReader(textFile));
fr1.lines().forEach(consumer::storeLines);
}
String[] CLASSES = consumer.lines.toArray(new String[0]);
Mat image = Imgcodecs.imread("images/bird.jpg");
Size size = image.size();
int cols = image.cols();
int rows = image.rows();
double h = size.height;
double w = size.width;
int hh = (int)size.height;
int ww = (int)size.width;
Mat blob = org.opencv.dnn.Dnn.blobFromImage(image, 1.0, new Size(w, h), Scalar.all(0), true, false);
// Load the network
Net net = org.opencv.dnn.Dnn.readNetFromTensorflow(MODEL_WEIGHTS, TEXT_GRAPH);
net.setPreferableBackend(org.opencv.dnn.Dnn.DNN_BACKEND_OPENCV);
net.setPreferableTarget(org.opencv.dnn.Dnn.DNN_TARGET_CPU);
net.setInput(blob);
ArrayList<String> outputlayers = new ArrayList<String>();
ArrayList<Mat> outputMats = new ArrayList<Mat>();
outputlayers.add("detection_out_final");
outputlayers.add("detection_masks");
net.forward(outputMats,outputlayers);
Mat numClasses = outputMats.get(0);
numClasses = numClasses.reshape(1, (int)numClasses.total() / 7);
for (int i = 0; i < numClasses.rows(); ++i) {
double confidence = numClasses.get(i, 2)[0];
//System.out.println(confidence);
if (confidence > 0.2) {
int classId = (int) numClasses.get(i, 1)[0];
String label = CLASSES[classId] + ": " + confidence;
System.out.println(label);
int left = (int)(numClasses.get(i, 3)[0] * cols);
int top = (int)(numClasses.get(i, 4)[0] * rows);
int right = (int)(numClasses.get(i, 5)[0] * cols);
int bottom = (int)(numClasses.get(i, 6)[0] * rows);
System.out.println(left + " " + top + " " + right + " " + bottom);
}
}
Mat numMasks = outputMats.get(1);
So far so good. My problem now is trying to obtain the segmentation shapes from numMasks Mat.
The size gives 90x100, total 2025000 and type -1*-1*CV_32FC1, isCont=true, isSubmat=true.
I know I have to reshape too, perhaps like this:
numMasks = numMasks.reshape(1, (int)numMasks.total() / 90);
Any help would be greatly appreciated.
Further edit
I think the masks are 15 x 15.
90 x 100 x 15 x 15 gives 2025000 so that gives me the total I saw earlier so I need to resize a mask and mix with original image.
I'm currently trying to add some JUnit tests to my pathdrawing system in order to check if the calculations are right...
Currently I have:
Class to Test(MapRouteDrawer.java):
protected static double[] getCoords(PolynomialSplineFunction curve, double[] index) {
final double detailLevel = 1.0;//Tweak this value in order to achieve good rendering results
final double defaultCoordSize = index[index.length - 1];
final double[] coords = new double[(int)Math.round(detailLevel * defaultCoordSize) + 1];
final double stepSize = curve.getKnots()[curve.getKnots().length - 1] / coords.length;
double curValue = 0;
for (int i = 0; i < coords.length; i ++) {
coords[i] = curve.value(curValue);//gets y value of specified x value
curValue += stepSize;
}
return coords;
}
protected static double[] getIndex(Point[] points) {
final double[] index = new double[points.length];
if(index.length > 0){
index[0] = 0;
}
for (int i = 1; i < points.length; i++) {
index[i] = index[i - 1] + Math.sqrt(points[i - 1].distance(points[i]));
}
return index;
}
TestClass:
private Point[] dummyPoints = new Point[]{new Point(0,0), new Point(100,0), new Point(0,100)};//Some Points for Testing
//This returns a so called index - the squareroot distance between addedn on top of each other
private double[] dummyIndex = MapRouteDrawer.getIndex(dummyPoints);
#Test
public void testCurve(){
final double[] testYValues = new double[]{20, 40, 90};
final PolynomialSplineFunction testFunction = new SplineInterpolator().interpolate(dummyIndex, testYValues);//get a Spline-Interpolated curve
final double[] coords = MapRouteDrawer.getCoords(testFunction, dummyIndex);//Calls the function to test
final double factor = testFunction.getKnots()[testFunction.getKnots().length - 1] / coords.length;
assertEquals(testYValues[0] * factor, coords[(int)Math.round(dummyIndex[0])], 1);//Check if the coordinates are equal
assertEquals(testYValues[1] * factor, coords[(int)Math.round(dummyIndex[1])], 1);
assertEquals(testYValues[2] * factor, coords[(int)Math.round(dummyIndex[2])], 1);
}
This is working fine, but if you are familiar with JUnit you may notice the delta of 1 which is neccesary in order for this Test to work...
What I'm trying to achieve is this:
#Test
public void testCurve(){
final double[] testYValues = new double[]{20, 40, 90};
final PolynomialSplineFunction testFunction = new SplineInterpolator().interpolate(dummyIndex, testYValues);//get a Spline-Interpolated curve
final double[] coords = MapRouteDrawer.getCoords(testFunction, dummyIndex);//Calls the function to test
final double factor;//Unknown... should be dynamic, so it does not matter which detail level I chose
assertEquals(testYValues[0], coords[(int)Math.round(dummyIndex[0])] * factor, 0);//Check if the coordinates are equal
assertEquals(testYValues[1], coords[(int)Math.round(dummyIndex[1])] * factor, 0);//e.g. coords[(int)Math.round(dummyIndex[0])] * factor == 20 etc.
assertEquals(testYValues[2], coords[(int)Math.round(dummyIndex[2])] * factor, 0);
}
So that the first value in assertEquals() is 20, 40, 90 etc. and not a weird 21.39587576787686 (or similar) number and the delta is 0 (or 0.01 if there is no other way) and not 1 which I'm currently using
Because I'm using a detail level in my getCoords() method, which should be able to be adjusted without having to change the test, there is a need to make the "factor" in my test related to the coords-size.
How would I calculate the factor in order for the Test to succeed?
Any help is would be very much appreciated
I am trying to create a visual grid of this http://www.ibm.com/developerworks/library/j-coordconvert/ -Military Grid Reference System. I have the latitude/longitude to UTM and also to MGRS...which ar
17 T 330649 4689666
17TLG3064989666
But when going from MGRS to latitude I get the following:
[D#18e3f02a
public class CoordinateConversion {
public static void main(String args[]) {
CoordinateConversion test = new CoordinateConversion();
CoordinateConversion test2 = new CoordinateConversion();
test.latLon2UTM(35.58, 82.56);
System.out.println(test.latLon2UTM(42.340837, -83.055821));
System.out.println();
test2.latLon2UTM(35.58, 82.56);
System.out.println(test2.latLon2MGRUTM(42.340837, -83.055821));
CoordinateConversion test3 = new CoordinateConversion();
test3.latLon2UTM(35.58, 82.56);
//System.out.print(test3.mgrutm2LatLong(42.340837, -83.055821));
//System.out.println(test3.mgrutm2LatLong("02CNR0634657742"));
MGRUTM2LatLon mg = new MGRUTM2LatLon();
//mg.convertMGRUTMToLatLong("02CNR0634657742");
String MGRUTM = "17TLG3064989666";
System.out.println(mg.convertMGRUTMToLatLong(MGRUTM));
//for loop to be developed
}
public double[] utm2LatLon(String UTM) {
UTM2LatLon c = new UTM2LatLon();
return c.convertUTMToLatLong(UTM);
}
public double[] mgrutm2LatLon(String MGRUTM) {
MGRUTM2LatLon c = new MGRUTM2LatLon();
return c.convertMGRUTMToLatLong(MGRUTM);
}
}
and from this class:
public double[] convertMGRUTMToLatLong(String mgrutm) {
double[] latlon = {0.0, 0.0};
// 02CNR0634657742
int zone = Integer.parseInt(mgrutm.substring(0, 2));
String latZone = mgrutm.substring(2, 3);
String digraph1 = mgrutm.substring(3, 4);
String digraph2 = mgrutm.substring(4, 5);
easting = Double.parseDouble(mgrutm.substring(5, 10));
northing = Double.parseDouble(mgrutm.substring(10, 15));
LatZones lz = new LatZones();
double latZoneDegree = lz.getLatZoneDegree(latZone);
double a1 = latZoneDegree * 40000000 / 360.0;
double a2 = 2000000 * Math.floor(a1 / 2000000.0);
Digraphs digraphs = new Digraphs();
double digraph2Index = digraphs.getDigraph2Index(digraph2);
double startindexEquator = 1;
if ((1 + zone % 2) == 1) {
startindexEquator = 6;
}
double a3 = a2 + (digraph2Index - startindexEquator) * 100000;
if (a3 <= 0) {
a3 = 10000000 + a3;
}
northing = a3 + northing;
zoneCM = -183 + 6 * zone;
double digraph1Index = digraphs.getDigraph1Index(digraph1);
int a5 = 1 + zone % 3;
double[] a6 = {16, 0, 8};
double a7 = 100000 * (digraph1Index - a6[a5 - 1]);
easting = easting + a7;
setVariables();
double latitude = 0;
latitude = 180 * (phi1 - fact1 * (fact2 + fact3 + fact4)) / Math.PI;
if (latZoneDegree < 0) {
latitude = 90 - latitude;
}
double d = _a2 * 180 / Math.PI;
double longitude = zoneCM - d;
if (getHemisphere(latZone).equals("S")) {
latitude = -latitude;
}
latlon[0] = latitude;
latlon[1] = longitude;
return latlon;
}
I am trying not to get into a large library where I will have to learn things that may be time consuming.
So I am trying to loop so I go east (easting) and north (northing) and cannot get past the point where I have one point - latitude/longitude.
Hope I have asked my question clearly without stating too much.
Any help will be appreciated.
Thanks,
-Terry
Your result from convertMGRUTMToLatLong() is an array of doubles, and by default, arrays are converted to String in a rather unreadable format in Java. That's where the [D#18e3f02a comes from. Try System.out.println(Arrays.toString(mg.convertMGRUTMToLatLong(MGRUTM))); and you'll get a more readable output.
In the method convertMGRUTMToLatLong(String s) you are returning an array latlon (i.e an object).
It returns its hashcode which is probably u dont want.
You want to print the array values. So in your main method you replace below line;
System.out.println(mg.convertMGRUTMToLatLong(MGRUTM));
with
double[] a = mg.convertMGRUTMToLatLong(MGRUTM) ;
System.out.println(a[0]+" " + a[1] );
Hope that helps!
I have a basic wave generator in java but I need something to remove the clicks I get from when the amplitude of a wave changes sharply. Namely when I start/stop playing a wave, especially if I have a beeping tone.
Phrogz's answer on SO gave a really nice and simple function, but I'm not sure I'm implementing it right.
When I first tried to use it, I couldn't get it to work, but then I seem to remember it working very well... I have since fiddled about a lot with my code and now it doesn't seem to be working very well again.
So here's the closest I could get to an SSCCE:
If you play this you will notice that when the filtering is on (filter = true) the wave is much quieter and the clicks slightly less, but this seems mainly due to the decrease in volume. There is still a noticeable "hit" on each beep, that I don't want, and I don't remember being there before...
import javax.sound.sampled.*;
public class Oscillator{
private static int SAMPLE_RATE = 22050;
private static short MAX_AMPLITUDE = Short.MAX_VALUE;
private static AudioFormat af = null;
private static SourceDataLine line = null;
private int frequency = 440; //Hz
private int numLoops = 1000;
private int beep = 100;
// set to true to apply low-pass filter
private boolean filter = true;
// set the amount of "smoothing" here
private int smoothing = 100;
private double oldValue;
public Oscillator(){
prepareLine();
}
public static void main(String[] args) {
System.out.println("Playing oscillator");
Oscillator osc = new Oscillator();
osc.play();
}
private void prepareLine(){
af = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, SAMPLE_RATE, 16, 2, 4, SAMPLE_RATE, false);
try {
DataLine.Info info = new DataLine.Info(SourceDataLine.class, af);
if (!AudioSystem.isLineSupported(info)) {
System.out.println("Line does not support: " + af);
System.exit(0);
}
line = (SourceDataLine) AudioSystem.getLine(info);
line.open(af);
}
catch (Exception e) {
System.out.println(e.getMessage());
System.exit(0);
}
}
private void play() {
System.out.println("play");
int maxSize = (int) Math.round( (SAMPLE_RATE * af.getFrameSize())/ frequency );
byte[] samples = new byte[maxSize];
line.start();
double volume = 1;
int count = 0;
for (int i = 0; i < numLoops; i ++){
if (count == beep) {
if(volume==1) volume = 0;
else volume = 1;
count = 0;
}
count ++;
playWave(frequency, volume, samples);
}
line.drain();
line.stop();
line.close();
System.exit(0);
}
private void playWave(int frequency, double volLevel, byte[] samples) {
double amplitude = volLevel * MAX_AMPLITUDE;
int numSamplesInWave = (int) Math.round( ((double) SAMPLE_RATE)/frequency );
int index = 0;
for (int i = 0; i < numSamplesInWave; i++) {
double theta = (double)i/numSamplesInWave;
double wave = getWave(theta);
int sample = (int) (wave * amplitude);
if (filter) sample = applyLowPassFilter(sample);
// left sample
samples[index + 0] = (byte) (sample & 0xFF);
samples[index + 1] = (byte) ((sample >> 8) & 0xFF);
// right sample
samples[index + 2] = (byte) (sample & 0xFF);
samples[index + 3] = (byte) ((sample >> 8) & 0xFF);
index += 4;
}
int offset = 0;
while (offset < index){
double increment =line.write(samples, offset, index-offset);
offset += increment;
}
}
private double getWave(double theta){
double value = 0;
theta = theta * 2 * Math.PI;
value = getSin(theta);
//value = getSqr(theta);
return value;
}
private double getSin(double theta){
return Math.sin(theta);
}
private int getSqr(double theta){
if (theta <= Math.PI) return 1;
else return 0;
}
// implementation of basic low-pass filter
private int applyLowPassFilter(int sample){
int newValue = sample;
double filteredValue = oldValue + (newValue - oldValue) / smoothing;
oldValue = filteredValue;
return (int) filteredValue;
}
}
The relevant method is at the end. If anyone does test this, please be careful of the volume if you have headphones!
So either:
It is working and I'm just expecting too much of such a simple implementation
I'm doing something wrong, stupid and obvious...
If it's just 1. How should/could I get rid of that harsh beat/hit/click from sudden amplitude changes?
If it's 2. good, should be a v short answer for a too long question.
A low pass filter will not remove clicks from sudden amplitude changes. Instead you need to avoid sudden amplitude changes.
You could use the lowpass filter to filter your amplitude level.
**Pseudo code**
for i = 0 to numSamplesInWave-1 do
begin
theta = i / numSamplesInWave;
wave = getWave(theta);
currentAmplitude = applyLowPassFilter(TargetAmplitude);
Sample[i] = wave * currentAmplitude;
end;
Using a lowpass filter as above is fine for smoothing input values. For example when the user changes a volume control.
In other situations it might be more appropriate to create an envelope of some sort. For example synthesizers commonly use ADSR envelopes to smooth the amplitude changes when a new Voice/Sound starts and stops.