Centroid of Buffer - java

I was trying to build innerbuffers . My task is it to make buffer from polygon so small that the new buffers were maximal 5% of the original size of the polygon but never 0!
I was trying something like that:
public Point getInnerBufferCentroid(MapContent mapContent) throws Exception {
JLabel label = new JLabel("Wählen Sie einen Layer aus:");
List<Layer> layerList = mapContent.layers();
String[] layerNames = new String[layerList.size()];
for (int i = 0; i < layerList.size(); i++) {
layerNames[i] = layerList.get(i).getFeatureSource().getName().toString();
}
String selectedLayer = (String) JOptionPane.showInputDialog(null, label,
"Layerauswahl", JOptionPane.QUESTION_MESSAGE, null, layerNames, layerNames[0]);
FeatureLayer selectedFeatureLayer = null;
for (Layer layer : layerList) {
if (layer.getFeatureSource().getName().toString().equals(selectedLayer)) {
selectedFeatureLayer = (FeatureLayer) layer;
break;
}
}
SimpleFeatureSource featureSource = (SimpleFeatureSource)
selectedFeatureLayer.getFeatureSource();
SimpleFeatureCollection featureCollection = featureSource.getFeatures();
SimpleFeatureIterator featureIterator = featureCollection.features();
SimpleFeature feature = featureIterator.next();
Geometry geometry = (Geometry) feature.getDefaultGeometry();
double originalArea = geometry.getArea();
double bufferArea = originalArea;
Geometry buffer = geometry.buffer(0);
while (bufferArea >= originalArea * 0.05 && bufferArea > 0) {
buffer = buffer.buffer(-1);
bufferArea = buffer.getArea();
}
Point centroid;
if (buffer instanceof Polygon) {
centroid = ((Polygon) buffer).getInteriorPoint();
} else {
MultiPolygon multiPolygon = (MultiPolygon) buffer;
int numGeometries = multiPolygon.getNumGeometries();
Polygon largestPolygon = null;
double largestArea = 0;
for (int i = 0; i < numGeometries; i++) {
Polygon polygon = (Polygon) multiPolygon.getGeometryN(i);
double area = polygon.getArea();
if (area > largestArea) {
largestArea = area;
largestPolygon = polygon;
}
}
centroid = largestPolygon.getCentroid();
}
return centroid;
}
but getInteriorPoint() and geCEntroid aren't existing. Did someone know a other strategy?

Related

how to use Yolo v3 with Java to detect objects (cows to be specific) in pictures:

I am working on some examples I found online to understand more about Yolo usage in java. I got this code that I edited a little and it can detect objects in videos but now I want to do it with Pictures and I am kinda struggling with it. I would appreciate if anyone can show me how to edit it or has an advise or a method to solve it .
The code:
`class yolo {
private static List<String> getOutputNames(Net net) {
List<String> names = new ArrayList<>();
List<Integer> outLayers = net.getUnconnectedOutLayers().toList();
List<String> layersNames = net.getLayerNames();
outLayers.forEach((item) -> names.add(layersNames.get(item - 1)));//unfold and create R-CNN layers from the loaded YOLO model//
return names;
}
public static void main(String[] args) throws InterruptedException {
System.load("C:\\Users\\LENOVO\\Desktop\\Java1\\Yolo\\opencv\\build\\java\\x64\\opencv_java400.dll");
System.out.println("Library Loaded");
System.load("C:\\Users\\LENOVO\\Desktop\\Java1\\Yolo\\opencv\\build\\java\\x64\\opencv_java400.dll");
String modelWeights = "C:\\Users\\LENOVO\\Desktop\\Java1\\Yolo\\yolov3.weights";
String modelConfiguration = "C:\\Users\\LENOVO\\Desktop\\Java1\\Yolo\\yolov3.cfg.txt";
String filePath = "C:\\Users\\LENOVO\\Desktop\\cows.mp4";
VideoCapture cap = new VideoCapture(filePath);
Mat frame = new Mat();
Mat dst = new Mat ();
//cap.read(frame);
JFrame jframe = new JFrame("Video");
JLabel vidpanel = new JLabel();
jframe.setContentPane(vidpanel);
jframe.setSize(600, 600);
jframe.setVisible(true);
Net net = Dnn.readNetFromDarknet(modelConfiguration, modelWeights);
//Thread.sleep(5000);
//Mat image = Imgcodecs.imread("D:\\yolo-object-detection\\yolo-object-detection\\images\\soccer.jpg");
Size sz = new Size(288,288);
List<Mat> result = new ArrayList<>();
List<String> outBlobNames = getOutputNames(net);
while (true) {
if (cap.read(frame)) {
Mat blob = Dnn.blobFromImage(frame, 0.00392, sz, new Scalar(0), true, false);
net.setInput(blob);
net.forward(result, outBlobNames);
// outBlobNames.forEach(System.out::println);
// result.forEach(System.out::println);
float confThreshold = 0.6f;
List<Integer> clsIds = new ArrayList<>();
List<Float> confs = new ArrayList<>();
List<Rect> rects = new ArrayList<>();
for (int i = 0; i < result.size(); ++i)
{
Mat level = result.get(i);
for (int j = 0; j < level.rows(); ++j)
{
Mat row = level.row(j);
Mat scores = row.colRange(5, level.cols());
Core.MinMaxLocResult mm = Core.minMaxLoc(scores);
float confidence = (float)mm.maxVal;
Point classIdPoint = mm.maxLoc;
if (confidence > confThreshold)
{
int centerX = (int)(row.get(0,0)[0] * frame.cols());
int centerY = (int)(row.get(0,1)[0] * frame.rows());
int width = (int)(row.get(0,2)[0] * frame.cols());
int height = (int)(row.get(0,3)[0] * frame.rows());
int left = centerX - width / 2;
int top = centerY - height / 2;
clsIds.add((int)classIdPoint.x);
confs.add((float)confidence);
rects.add(new Rect(left, top, width, height));
}
}
}
float nmsThresh = 0.5f;
MatOfFloat confidences = new MatOfFloat(Converters.vector_float_to_Mat(confs));
Rect[] boxesArray = rects.toArray(new Rect[0]);
MatOfRect boxes = new MatOfRect(boxesArray);
MatOfInt indices = new MatOfInt();
Dnn.NMSBoxes(boxes, confidences, confThreshold, nmsThresh, indices);
int [] ind = indices.toArray();
int j=0;
for (int i = 0; i < ind.length; ++i)
{
int idx = ind[i];
Rect box = boxesArray[idx];
Imgproc.rectangle(frame, box.tl(), box.br(), new Scalar(0,0,255), 2);
//i=j;
System.out.println(idx);
}
// Imgcodecs.imwrite("D://out.png", image);
//System.out.println("Image Loaded");
ImageIcon image = new ImageIcon(Mat2bufferedImage(frame));
vidpanel.setIcon(image);
vidpanel.repaint();
// System.out.println(j);
//System.out.println("Done");
}
}
}
// }
private static BufferedImage Mat2bufferedImage(Mat image) {
MatOfByte bytemat = new MatOfByte();
Imgcodecs.imencode(".jpg", image, bytemat);
byte[] bytes = bytemat.toArray();
InputStream in = new ByteArrayInputStream(bytes);
BufferedImage img = null;
try {
img = ImageIO.read(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return img;
}`
`

OpenCV java One Line needed to Explain about Detection

sorry for my question i'm going to learn about openCv in java and one example i found that have line with something i can't understand
detections = detections.reshape(1, (int)detections.total() / 7);
From full code :
public class DeepNeuralNetworkProcessor {
private Net net;
private final String[] classNames = {"background",
"aeroplane", "bicycle", "bird", "boat",
"bottle", "bus", "car", "cat", "chair",
"cow", "diningtable", "dog", "horse",
"motorbike", "person", "pottedplant",
"sheep", "sofa", "train", "tvmonitor"};
public DeepNeuralNetworkProcessor() {
this.net = Dnn.readNetFromCaffe(Files_Path.DDN_PROTO, Files_Path.DDN_MODEL);
}
public List<DnnObject> getObjectsInFrame(Mat frame, boolean isGrayFrame) {
int inWidth = 320;
int inHeight = 240;
double inScaleFactor = 0.007843;
double thresholdDnn = 0.2;//Minimum value to detect the object
double meanVal = 127.5;
Mat blob = null;
Mat detections = null;
List<DnnObject> objectList = new ArrayList<>();
int cols = frame.cols();
int rows = frame.rows();
try {
if (isGrayFrame)
Imgproc.cvtColor(frame, frame, Imgproc.COLOR_GRAY2RGB);
blob = Dnn.blobFromImage(frame, inScaleFactor,
new Size(inWidth, inHeight),
new Scalar(meanVal, meanVal, meanVal),
false, false);
net.setInput(blob);
detections = net.forward();
detections = detections.reshape(1, (int) detections.total() / 7);
//all detected objects
for (int i = 0; i < detections.rows(); ++i) {
double confidence = detections.get(i, 2)[0];
if (confidence < thresholdDnn)
continue;
int classId = (int) detections.get(i, 1)[0];
//...
}
} catch (Exception ex) {
ex.printStackTrace();
}
return objectList;
}
}
can anyone explain what this line does ?
or better clear explain about the detection mat.
and what net.forward do?
please send me some reference for java opencv or deeplearning4j

Apache POI - When editing chart data in a Word file, it returns to the data defined in the form

I have developed a Word function that includes a Chart.
When editing chart data in a Word file, it returns to the data defined in the form.
Here are the steps:
I edit word(docx) xml data and workbook.
I open microsoft office - the data shown is normal.
I click Chart data edit function - it returns the original data.
library - ooxml-schemas-1.3, poi-4.0.0-SNAPSHOT
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String inFilePath = "../file/temp/TEMP_Chart_Simple.docx";
String outFilePath = "../file/out/NEW_Chart_" + System.currentTimeMillis() + ".docx";
Map<String, Map<String, String>> CHART_MAP_DATA = new LinkedHashMap<>();
Map<String, String> inData = new LinkedHashMap<>();
inData.put("1", "8.3");
inData.put("2", "7.3");
CHART_MAP_DATA.put("temp", inData);
Path path = Paths.get(inFilePath);
byte[] byteData = Files.readAllBytes(path);
// read as XWPFDocument from byte[]
XWPFDocument document = new XWPFDocument(new ByteArrayInputStream(byteData));
XWPFChart xChart = null;
CTChart ctChart = null;
XSSFWorkbook wb = null;
for (POIXMLDocumentPart part : document.getRelations()) {
if (part instanceof XWPFChart) {
xChart = (XWPFChart) part;
wb = xChart.getWorkbook();
ctChart = xChart.getCTChart();
if(getTitle(ctChart).equals("FIELD_CHART")) {
break;
}
}
}
CTPlotArea plotArea = ctChart.getPlotArea();
List<CTBarChart> arBarChart = plotArea.getBarChartList();
List<CTBarSer> arBarSer = arBarChart.get(0).getSerList();
if(CHART_MAP_DATA != null && !CHART_MAP_DATA.isEmpty()) {
Set<String> keys = CHART_MAP_DATA.keySet();
Iterator<String> itKeys = keys.iterator();
while(itKeys.hasNext()) {
String inKey = itKeys.next();
Map<String, String> barData = CHART_MAP_DATA.get(inKey);
setBarChartData(ctChart, serCnt, inKey, barData);
}
}
XSSFSheet sheet = wb.getSheetAt(0);
sheet.getRow(1).getCell(1).setCellValue(8.3);
sheet.getRow(2).getCell(1).setCellValue(7.3);
FileOutputStream fos = new FileOutputStream(new File(outFilePath));
document.write(fos);
fos.close();
document.close();
}
public static void setBarChartData(CTChart ctChart, int serIdx, String series, Map<String, String> data) {
CTPlotArea plotArea = ctChart.getPlotArea();
List<CTBarChart> arBarChart = plotArea.getBarChartList();
if(arBarChart.size() > 0) {
List<CTBarSer> arBarSer = arBarChart.get(0).getSerList();
CTBarSer barSer = arBarSer.get(serIdx);
CTSerTx serTx = barSer.getTx();
CTStrRef strRef = serTx.getStrRef();
CTStrData strData = strRef.getStrCache();
List<CTStrVal> arStrVal = strData.getPtList();
for(int b=0; b<arStrVal.size(); b++) {
arStrVal.get(b).setV(series);
}
CTAxDataSource dataSource = barSer.getCat();
CTStrRef dStrRef = dataSource.getStrRef();
boolean isCatDataTypeStr = true;
List<CTStrVal> arDStrVal = null;
List<CTNumVal> arDNumVal = null;
CTStrData dStrData = null;
CTNumData dNumData = null;
if(dStrRef != null) {
dStrData = dStrRef.getStrCache();
arDStrVal = dStrData.getPtList();
dStrData.getPtCount().setVal(data.size());
if(arDStrVal.size() > data.size()) {
for(int i=arDStrVal.size(); i>data.size(); i--) {
dStrData.removePt(i-1);
}
}
isCatDataTypeStr = true;
} else {
CTNumRef dNumRef = dataSource.getNumRef();
dNumData = dNumRef.getNumCache();
arDNumVal = dNumData.getPtList();
dNumData.getPtCount().setVal(data.size());
if(arDNumVal.size() > data.size()) {
for(int i=arDNumVal.size(); i>data.size(); i--) {
dNumData.removePt(i-1);
}
}
isCatDataTypeStr = false;
}
CTNumDataSource numDataSource = barSer.getVal();
CTNumRef numRef = numDataSource.getNumRef();
CTNumData numData = numRef.getNumCache();
List<CTNumVal> arNumVal = numData.getPtList();
numData.getPtCount().setVal(data.size());
if(arNumVal.size() > data.size()) {
for(int i=arNumVal.size(); i>data.size(); i--) {
numData.removePt(i-1);
}
}
Set<String> keys = data.keySet();
Iterator<String> itKeys = keys.iterator();
int valSize = 0;
if(isCatDataTypeStr) {
valSize = arDStrVal.size();
} else {
valSize = arDNumVal.size();
}
int idx = 0;
while(itKeys.hasNext()) {
String stKey = itKeys.next();
if(valSize > idx) {
if(isCatDataTypeStr) {
arDStrVal.get(idx).setV(stKey);
} else {
arDNumVal.get(idx).setV(stKey);
}
} else {
if(isCatDataTypeStr) {
CTStrVal val = dStrData.addNewPt();
val.setIdx(idx);
val.setV(stKey);
} else {
CTNumVal val = dNumData.addNewPt();
val.setIdx(idx);
val.setV(stKey);
}
}
if(arNumVal.size() > idx) {
arNumVal.get(idx).setV(data.get(stKey));
} else {
CTNumVal val = numData.addNewPt();
val.setIdx(idx);
val.setV(data.get(stKey));
}
idx++;
}
}
}
public static String getTitle(CTChart chart) {
CTTitle title = chart.getTitle();
if (title != null) {
CTTx tx = title.getTx();
CTTextBody tb = tx.getRich();
return tb.getPArray(0).getRArray(0).getT();
}
return "";
}
Using apache poi 4.0.1 changing XDDFChart data needs parallel updating all changes in underlying chart data workbook and the chart itself. The chart holds the cached data while the workbook holds the source data. But both is possible using the high level apache poiclasses. No access to underlying XML beans needed.
Example
Word template which has template chart having 2 series and 3 categories:
Code:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.xddf.usermodel.chart.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.ss.util.CellRangeAddress;
public class WordChangeChartData {
public static void main(String[] args) throws Exception {
String filePath = "TEMP_Chart_SimpleBar.docx"; // has template chart having 2 series, 3 categories
String filePathNew = "New_Chart_Simple.docx";
Object[][] data = new Object[][] { // 2 series, 3 categories
{"", "male", "female"}, // series titles
{"health", 123d, 234d}, // category 1
{"amount", 345d, 123d}, // category 2
{"size", 180d, 160d} // category 3
};
XWPFDocument document = new XWPFDocument(new FileInputStream(filePath));
XWPFChart chart = document.getCharts().get(0);
XSSFWorkbook chartDataWorkbook = chart.getWorkbook();
String sheetName = chartDataWorkbook.getSheetName(0);
XSSFSheet chartDataSheet = chartDataWorkbook.getSheet(sheetName);
if (chart.getChartSeries().size() == 1) { // only one chart data
XDDFChartData chartData = chart.getChartSeries().get(0);
if (chartData.getSeries().size() == 2) { // exact two series
int rMin = 1;
int rMax = 3;
// set new category data (both series)
XDDFCategoryDataSource category = null;
int c = 0;
for (int r = rMin; r < rMax+1; r++) {
chartDataSheet.getRow(r).getCell(c).setCellValue((String)data[r][c]); // in sheet
}
category = XDDFDataSourcesFactory.fromStringCellRange(chartDataSheet, new CellRangeAddress(rMin,rMax,c,c)); // in chart
// series 1
XDDFChartData.Series series1 = chartData.getSeries().get(0);
c = 1;
// set new title
String series1Title = (String)data[0][c];
chartDataSheet.getRow(0).getCell(c).setCellValue(series1Title); // in sheet
if (chartDataSheet.getTables().size() > 0) {
if (chartDataSheet.getTables().get(0).getCTTable().getTableColumns().getTableColumnList().size() > c)
chartDataSheet.getTables().get(0).getCTTable().getTableColumns().getTableColumnList().get(c).setName(series1Title);
}
series1.setTitle(series1Title, new CellReference(sheetName, 0, c, true, true)); // in chart
// set new values
XDDFNumericalDataSource<Double> values = null;
for (int r = rMin; r < rMax+1; r++) {
chartDataSheet.getRow(r).getCell(c).setCellValue((Double)data[r][c]); // in sheet
}
values = XDDFDataSourcesFactory.fromNumericCellRange(chartDataSheet, new CellRangeAddress(rMin,rMax,c,c));
series1.replaceData(category, values);
series1.plot(); //in chart
// series 2
XDDFChartData.Series series2 = chartData.getSeries().get(1);
c = 2;
// set new title
String series2Title = (String)data[0][c];
chartDataSheet.getRow(0).getCell(c).setCellValue(series2Title); // in sheet
if (chartDataSheet.getTables().size() > 0) {
if (chartDataSheet.getTables().get(0).getCTTable().getTableColumns().getTableColumnList().size() > c)
chartDataSheet.getTables().get(0).getCTTable().getTableColumns().getTableColumnList().get(c).setName(series2Title);
}
series2.setTitle(series2Title, new CellReference(sheetName, 0, c, true, true)); // in chart
// set new values
for (int r = rMin; r < rMax+1; r++) {
chartDataSheet.getRow(r).getCell(c).setCellValue((Double)data[r][c]); // in sheet
}
values = XDDFDataSourcesFactory.fromNumericCellRange(chartDataSheet, new CellRangeAddress(rMin,rMax,c,c));
series2.replaceData(category, values);
series2.plot(); // in chart
}
}
FileOutputStream out = new FileOutputStream(filePathNew);
document.write(out);
out.close();
document.close();
}
}
Result:

How to use the 'svm_toy' Applet example in LibSVM?

I'm using LIBSVM. In the download package is a svm_toy.java file. I could not find out how it works. Here is the source code:
import libsvm.*;
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import java.io.*;
/**
* SVM package
* #author unknown
*
*/
public class svm_toy extends Applet {
static final String DEFAULT_PARAM="-t 2 -c 100";
int XLEN;
int YLEN;
// off-screen buffer
Image buffer;
Graphics buffer_gc;
// pre-allocated colors
final static Color colors[] =
{
new Color(0,0,0),
new Color(0,120,120),
new Color(120,120,0),
new Color(120,0,120),
new Color(0,200,200),
new Color(200,200,0),
new Color(200,0,200)
};
class point {
point(double x, double y, byte value)
{
this.x = x;
this.y = y;
this.value = value;
}
double x, y;
byte value;
}
Vector<point> point_list = new Vector<point>();
byte current_value = 1;
public void init()
{
setSize(getSize());
final Button button_change = new Button("Change");
Button button_run = new Button("Run");
Button button_clear = new Button("Clear");
Button button_save = new Button("Save");
Button button_load = new Button("Load");
final TextField input_line = new TextField(DEFAULT_PARAM);
BorderLayout layout = new BorderLayout();
this.setLayout(layout);
Panel p = new Panel();
GridBagLayout gridbag = new GridBagLayout();
p.setLayout(gridbag);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.gridwidth = 1;
gridbag.setConstraints(button_change,c);
gridbag.setConstraints(button_run,c);
gridbag.setConstraints(button_clear,c);
gridbag.setConstraints(button_save,c);
gridbag.setConstraints(button_load,c);
c.weightx = 5;
c.gridwidth = 5;
gridbag.setConstraints(input_line,c);
button_change.setBackground(colors[current_value]);
p.add(button_change);
p.add(button_run);
p.add(button_clear);
p.add(button_save);
p.add(button_load);
p.add(input_line);
this.add(p,BorderLayout.SOUTH);
button_change.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_change_clicked(); button_change.setBackground(colors[current_value]); }});
button_run.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_run_clicked(input_line.getText()); }});
button_clear.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_clear_clicked(); }});
button_save.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_save_clicked(input_line.getText()); }});
button_load.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_load_clicked(); }});
input_line.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_run_clicked(input_line.getText()); }});
this.enableEvents(AWTEvent.MOUSE_EVENT_MASK);
}
void draw_point(point p)
{
Color c = colors[p.value+3];
Graphics window_gc = getGraphics();
buffer_gc.setColor(c);
buffer_gc.fillRect((int)(p.x*XLEN),(int)(p.y*YLEN),4,4);
window_gc.setColor(c);
window_gc.fillRect((int)(p.x*XLEN),(int)(p.y*YLEN),4,4);
}
void clear_all()
{
point_list.removeAllElements();
if(buffer != null)
{
buffer_gc.setColor(colors[0]);
buffer_gc.fillRect(0,0,XLEN,YLEN);
}
repaint();
}
void draw_all_points()
{
int n = point_list.size();
for(int i=0;i<n;i++)
draw_point(point_list.elementAt(i));
}
void button_change_clicked()
{
++current_value;
if(current_value > 3) current_value = 1;
}
private static double atof(String s)
{
return Double.valueOf(s).doubleValue();
}
private static int atoi(String s)
{
return Integer.parseInt(s);
}
void button_run_clicked(String args)
{
// guard
if(point_list.isEmpty()) return;
svm_parameter param = new svm_parameter();
// default values
param.svm_type = svm_parameter.C_SVC;
param.kernel_type = svm_parameter.RBF;
param.degree = 3;
param.gamma = 0;
param.coef0 = 0;
param.nu = 0.5;
param.cache_size = 40;
param.C = 1;
param.eps = 1e-3;
param.p = 0.1;
param.shrinking = 1;
param.probability = 0;
param.nr_weight = 0;
param.weight_label = new int[0];
param.weight = new double[0];
// parse options
StringTokenizer st = new StringTokenizer(args);
String[] argv = new String[st.countTokens()];
for(int i=0;i<argv.length;i++)
argv[i] = st.nextToken();
for(int i=0;i<argv.length;i++)
{
if(argv[i].charAt(0) != '-') break;
if(++i>=argv.length)
{
System.err.print("unknown option\n");
break;
}
switch(argv[i-1].charAt(1))
{
case 's':
param.svm_type = atoi(argv[i]);
break;
case 't':
param.kernel_type = atoi(argv[i]);
break;
case 'd':
param.degree = atoi(argv[i]);
break;
case 'g':
param.gamma = atof(argv[i]);
break;
case 'r':
param.coef0 = atof(argv[i]);
break;
case 'n':
param.nu = atof(argv[i]);
break;
case 'm':
param.cache_size = atof(argv[i]);
break;
case 'c':
param.C = atof(argv[i]);
break;
case 'e':
param.eps = atof(argv[i]);
break;
case 'p':
param.p = atof(argv[i]);
break;
case 'h':
param.shrinking = atoi(argv[i]);
break;
case 'b':
param.probability = atoi(argv[i]);
break;
case 'w':
++param.nr_weight;
{
int[] old = param.weight_label;
param.weight_label = new int[param.nr_weight];
System.arraycopy(old,0,param.weight_label,0,param.nr_weight-1);
}
{
double[] old = param.weight;
param.weight = new double[param.nr_weight];
System.arraycopy(old,0,param.weight,0,param.nr_weight-1);
}
param.weight_label[param.nr_weight-1] = atoi(argv[i-1].substring(2));
param.weight[param.nr_weight-1] = atof(argv[i]);
break;
default:
System.err.print("unknown option\n");
}
}
// build problem
svm_problem prob = new svm_problem();
prob.l = point_list.size();
prob.y = new double[prob.l];
if(param.kernel_type == svm_parameter.PRECOMPUTED)
{
}
else if(param.svm_type == svm_parameter.EPSILON_SVR ||
param.svm_type == svm_parameter.NU_SVR)
{
if(param.gamma == 0) param.gamma = 1;
prob.x = new svm_node[prob.l][1];
for(int i=0;i<prob.l;i++)
{
point p = point_list.elementAt(i);
prob.x[i][0] = new svm_node();
prob.x[i][0].index = 1;
prob.x[i][0].value = p.x;
prob.y[i] = p.y;
}
// build model & classify
svm_model model = svm.svm_train(prob, param);
svm_node[] x = new svm_node[1];
x[0] = new svm_node();
x[0].index = 1;
int[] j = new int[XLEN];
Graphics window_gc = getGraphics();
for (int i = 0; i < XLEN; i++)
{
x[0].value = (double) i / XLEN;
j[i] = (int)(YLEN*svm.svm_predict(model, x));
}
buffer_gc.setColor(colors[0]);
buffer_gc.drawLine(0,0,0,YLEN-1);
window_gc.setColor(colors[0]);
window_gc.drawLine(0,0,0,YLEN-1);
int p = (int)(param.p * YLEN);
for(int i=1;i<XLEN;i++)
{
buffer_gc.setColor(colors[0]);
buffer_gc.drawLine(i,0,i,YLEN-1);
window_gc.setColor(colors[0]);
window_gc.drawLine(i,0,i,YLEN-1);
buffer_gc.setColor(colors[5]);
window_gc.setColor(colors[5]);
buffer_gc.drawLine(i-1,j[i-1],i,j[i]);
window_gc.drawLine(i-1,j[i-1],i,j[i]);
if(param.svm_type == svm_parameter.EPSILON_SVR)
{
buffer_gc.setColor(colors[2]);
window_gc.setColor(colors[2]);
buffer_gc.drawLine(i-1,j[i-1]+p,i,j[i]+p);
window_gc.drawLine(i-1,j[i-1]+p,i,j[i]+p);
buffer_gc.setColor(colors[2]);
window_gc.setColor(colors[2]);
buffer_gc.drawLine(i-1,j[i-1]-p,i,j[i]-p);
window_gc.drawLine(i-1,j[i-1]-p,i,j[i]-p);
}
}
}
else
{
if(param.gamma == 0) param.gamma = 0.5;
prob.x = new svm_node [prob.l][2];
for(int i=0;i<prob.l;i++)
{
point p = point_list.elementAt(i);
prob.x[i][0] = new svm_node();
prob.x[i][0].index = 1;
prob.x[i][0].value = p.x;
prob.x[i][1] = new svm_node();
prob.x[i][1].index = 2;
prob.x[i][1].value = p.y;
prob.y[i] = p.value;
}
// build model & classify
svm_model model = svm.svm_train(prob, param);
svm_node[] x = new svm_node[2];
x[0] = new svm_node();
x[1] = new svm_node();
x[0].index = 1;
x[1].index = 2;
Graphics window_gc = getGraphics();
for (int i = 0; i < XLEN; i++)
for (int j = 0; j < YLEN ; j++) {
x[0].value = (double) i / XLEN;
x[1].value = (double) j / YLEN;
double d = svm.svm_predict(model, x);
if (param.svm_type == svm_parameter.ONE_CLASS && d<0) d=2;
buffer_gc.setColor(colors[(int)d]);
window_gc.setColor(colors[(int)d]);
buffer_gc.drawLine(i,j,i,j);
window_gc.drawLine(i,j,i,j);
}
}
draw_all_points();
}
void button_clear_clicked()
{
clear_all();
}
void button_save_clicked(String args)
{
FileDialog dialog = new FileDialog(new Frame(),"Save",FileDialog.SAVE);
dialog.setVisible(true);
String filename = dialog.getDirectory() + dialog.getFile();
if (filename == null) return;
try {
DataOutputStream fp = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(filename)));
int svm_type = svm_parameter.C_SVC;
int svm_type_idx = args.indexOf("-s ");
if(svm_type_idx != -1)
{
StringTokenizer svm_str_st = new StringTokenizer(args.substring(svm_type_idx+2).trim());
svm_type = atoi(svm_str_st.nextToken());
}
int n = point_list.size();
if(svm_type == svm_parameter.EPSILON_SVR || svm_type == svm_parameter.NU_SVR)
{
for(int i=0;i<n;i++)
{
point p = point_list.elementAt(i);
fp.writeBytes(p.y+" 1:"+p.x+"\n");
}
}
else
{
for(int i=0;i<n;i++)
{
point p = point_list.elementAt(i);
fp.writeBytes(p.value+" 1:"+p.x+" 2:"+p.y+"\n");
}
}
fp.close();
} catch (IOException e) { System.err.print(e); }
}
void button_load_clicked()
{
FileDialog dialog = new FileDialog(new Frame(),"Load",FileDialog.LOAD);
dialog.setVisible(true);
String filename = dialog.getDirectory() + dialog.getFile();
if (filename == null) return;
clear_all();
try {
BufferedReader fp = new BufferedReader(new FileReader(filename));
String line;
while((line = fp.readLine()) != null)
{
StringTokenizer st = new StringTokenizer(line," \t\n\r\f:");
if(st.countTokens() == 5)
{
byte value = (byte)atoi(st.nextToken());
st.nextToken();
double x = atof(st.nextToken());
st.nextToken();
double y = atof(st.nextToken());
point_list.addElement(new point(x,y,value));
}
else if(st.countTokens() == 3)
{
double y = atof(st.nextToken());
st.nextToken();
double x = atof(st.nextToken());
point_list.addElement(new point(x,y,current_value));
}else
break;
}
fp.close();
} catch (IOException e) { System.err.print(e); }
draw_all_points();
}
protected void processMouseEvent(MouseEvent e)
{
if(e.getID() == MouseEvent.MOUSE_PRESSED)
{
if(e.getX() >= XLEN || e.getY() >= YLEN) return;
point p = new point((double)e.getX()/XLEN,
(double)e.getY()/YLEN,
current_value);
point_list.addElement(p);
draw_point(p);
}
}
public void paint(Graphics g)
{
// create buffer first time
if(buffer == null) {
buffer = this.createImage(XLEN,YLEN);
buffer_gc = buffer.getGraphics();
buffer_gc.setColor(colors[0]);
buffer_gc.fillRect(0,0,XLEN,YLEN);
}
g.drawImage(buffer,0,0,this);
}
public Dimension getPreferredSize() { return new Dimension(XLEN,YLEN+50); }
public void setSize(Dimension d) { setSize(d.width,d.height); }
public void setSize(int w,int h) {
super.setSize(w,h);
XLEN = w;
YLEN = h-50;
clear_all();
}
public static void main(String[] argv)
{
new AppletFrame("svm_toy",new svm_toy(),500,500+50);
}
}
class AppletFrame extends Frame {
AppletFrame(String title, Applet applet, int width, int height)
{
super(title);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
applet.init();
applet.setSize(width,height);
applet.start();
this.add(applet);
this.pack();
this.setVisible(true);
}
}
Could someone give me an example or explanation? I also would like to scale my training data. Where is the right place to scale?
Thanks
SVM-Toy
SVM Toy is - as the name suggests - a simple toy build by the LIBSVM dev team and is not recommended for "productive" visualization of the SVM's decision boundary.
Moreover looking into the source-code of svm_toy it becomes clear, that this tool only supports 2D vectors.
Relevant code fragment is taken from the button_load_clicked() Method:
while ((line = fp.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, " \t\n\r\f:");
if (st.countTokens() == 5) {
byte value = (byte) atoi(st.nextToken());
st.nextToken();
double x = atof(st.nextToken());
st.nextToken();
double y = atof(st.nextToken());
point_list.addElement(new point(x, y, value));
} else if (st.countTokens() == 3) {
double y = atof(st.nextToken());
st.nextToken();
double x = atof(st.nextToken());
point_list.addElement(new point(x, y, current_value));
} else {
break;
}
}
As you can see, the svm_toy implementation can only handle 2D vectors, which means it only supports vectors, which were constructed out of two features.
That means, you can only read and display files which are build from only two features like for example the fourclass dataset provided by the LIBSVM authors. However it seems, that this feature is not supported within this implementation.
I think, that the tool is designed for interactive visualization. You are able to change the color and click on the black application screen. After you set some points (each color representing an own class), you can click "run" and the decision boundary is displayed.
Displaying the desicion boundary in an high dimensional vector space is even nearly impossible. I would recommend to not use this tool implementation for any productive / scientific purpose.
Scaling
Scaling of your training data should be done after you transformed it into it's numeric representation and before you are going forward to train your SVM with this data.
In short that means, you have to do the following steps before using svm_train
Construct the numeric representation for each data point (with the help of feature selection, ...)
Analyse the resulting numeric representation for each data point
Scale your data for example to [-1,1]
Go ahead and train your SVM model. Note well, that you have to repeat 1-3 for predicting unknown data points. The only difference is, that you already know the necessary features, so there is no need for feature selection.

Loading .obj file strange results

I'm writing a Java LWJGL 3D game-engine. I decided to rewrite my mesh class and the .obj loader. The mesh class works fine when putting in data manually, but wehn loading from an .obj-file it gives some strange results: (it's supposed to be a dragon but lokks like a 2D ... something)
public static Mesh loadMesh(String fileName) throws IOException
{
String splitArray[] = fileName.split("\\.");
String ext = splitArray[splitArray.length-1];
if(!ext.equals("obj"))
System.err.println("Error: Engine can only load .obj files, try converting the file: " + fileName);
ArrayList<Vector3f> vertices = new ArrayList<Vector3f>();
ArrayList<Integer> vindices = new ArrayList<Integer>();
ArrayList<Integer> tindices = new ArrayList<Integer>();
ArrayList<Integer> nindices = new ArrayList<Integer>();
ArrayList<Vector3f> normals = new ArrayList<Vector3f>();
ArrayList<Vector2f> texCoords = new ArrayList<Vector2f>();
BufferedReader reader = new BufferedReader(new FileReader("./res/models/"+fileName));
String line = "";
while((line=reader.readLine())!=null)
{
String[] p = line.split(" ");
if(line.startsWith("v"))
{
vertices.add(new Vector3f(Float.valueOf(p[1]),
Float.valueOf(p[2]),
Float.valueOf(p[3])));
}
if(line.startsWith("vn"))
{
normals.add(new Vector3f(Float.valueOf(p[1]),
Float.valueOf(p[2]),
Float.valueOf(p[3])));
}
if(line.startsWith("vt"))
{
texCoords.add(new Vector2f(Float.valueOf(p[1]),
Float.valueOf(p[2])));
}
if(line.startsWith("f"))
{
String[] arg1 = p[1].split("/");
String[] arg2 = p[2].split("/");
String[] arg3 = p[3].split("/");
vindices.add(Integer.parseInt(arg1[0]));
if(arg1.length>1)
tindices.add(Integer.parseInt(arg1[1]));
if(arg1.length>2)
nindices.add(Integer.parseInt(arg1[3]));
vindices.add(Integer.parseInt(arg2[0]));
if(arg1.length>1)
tindices.add(Integer.parseInt(arg2[1]));
if(arg2.length>2)
nindices.add(Integer.parseInt(arg2[3]));
vindices.add(Integer.parseInt(arg3[0]));
if(arg1.length>1)
tindices.add(Integer.parseInt(arg3[1]));
if(arg3.length>2)
nindices.add(Integer.parseInt(arg3[3]));
}
}
float[] vdata = new float[vertices.size() * 3];
float[] tdata = new float[texCoords.size() * 2];
float[] ndata = new float[normals.size() * 3];
for(int i = 0; i < vdata.length; i++)
{
vdata[i] = vertices.get(Integer.valueOf(vindices.get(i))).getX();
vdata[i++] = vertices.get(Integer.valueOf(vindices.get(i))).getY();
vdata[i++] = vertices.get(Integer.valueOf(vindices.get(i))).getZ();
}
for(int i = 0; i < ndata.length; i++)
{
ndata[i] = normals.get(Integer.valueOf(nindices.get(i))).getX();
ndata[i++] = normals.get(Integer.valueOf(nindices.get(i))).getY();
ndata[i++] = normals.get(Integer.valueOf(nindices.get(i))).getZ();
}
for(int i = 0; i < tdata.length; i++)
{
tdata[i] = texCoords.get(Integer.valueOf(tindices.get(i))).getX();
tdata[i++] = texCoords.get(Integer.valueOf(tindices.get(i))).getY();
}
return new Mesh(vdata, tdata, ndata);
}
thats my .obj-file loader. Can't see what is wrong...
Upon closer inspection there are some nice bugs:
vindices.add(Integer.parseInt(arg1[0]));
if(arg1.length>1)
tindices.add(Integer.parseInt(arg1[1]));
if(arg1.length>2)
nindices.add(Integer.parseInt(arg1[3])); // this should be 2 for the normals
and
for(int i = 0; i < vdata.length; i++)
{
vdata[i] = vertices.get(Integer.valueOf(vindices.get(i))).getX(); //i=0
vdata[i++] = vertices.get(Integer.valueOf(vindices.get(i))).getY(); //i=0 and counted up afterwards
vdata[i++] = vertices.get(Integer.valueOf(vindices.get(i))).getZ();//i=1 and counted up afterwards
}
This is what makes the mesh two-dimensional.
I would suggest using eigther ++i or
for(int i = 0; i < vdata.length; i+=3)
{
vdata[i] = vertices.get(Integer.valueOf(vindices.get(i))).getX();
vdata[i+1] = vertices.get(Integer.valueOf(vindices.get(i))).getY();
vdata[i+2] = vertices.get(Integer.valueOf(vindices.get(i))).getZ();
}

Categories

Resources