I wrote a practice app that solves quadratic equations and now I want to have the option to graph them with a button. Yet when I press the button the application crashes. Here is the code for the main program and the graphing one(located beneath):
Main class: *note: I do have the necessary classes imported and the .jar.
package com.test.quad;
import java.text.DecimalFormat;
import java.util.List;
import android.util.Log;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class QuadraticActivity extends Activity {
Button reset;
Button solve;
Button grapher;
TextView labela1;
TextView b1label;
TextView c1label;
TextView result1;
TextView result2;
EditText a1;
EditText b1;
EditText c1;
public List<double[]> x,y;
public double a, b, c;
public double xStart = 0, xEnd = 0;
public double xCurrent;
double yCurrent;
public double xStep;
public int count = 100;
Graph g = new Graph();
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
labela1 = (TextView)this.findViewById(R.id.labela1);
b1label = (TextView)this.findViewById(R.id.b1label);
c1label = (TextView)this.findViewById(R.id.c1label);
result1 = (TextView)this.findViewById(R.id.result1);
result2 = (TextView)this.findViewById(R.id.result2);
a1 = (EditText)this.findViewById(R.id.a1);
b1 = (EditText)this.findViewById(R.id.b1);
c1 = (EditText)this.findViewById(R.id.c1);
solve = (Button)this.findViewById(R.id.solve);
reset = (Button)this.findViewById(R.id.reset);
grapher = (Button)this.findViewById(R.id.grapher);
}
public void onClickHandler(View v) {
switch(v.getId()){
case R.id.reset:
a1.setText("");
b1.setText("");
c1.setText("");
result1.setText("");
result2.setText("");
a=0;
b=0;
c=0;
break;
case R.id.solve:
solveEquation();
break;
case R.id.grapher:
Intent achartIntent = new Graph().execute(this);
startActivity(achartIntent);
Log.d("debug", "clicked" );
break;
}
}
protected void solveEquation() {
try{
a = Double.parseDouble(a1.getText().toString());
b = Double.parseDouble(b1.getText().toString());
c = Double.parseDouble(c1.getText().toString());
}
catch (NumberFormatException exception) {
result1.setText("Please enter a number");
result2.setText(" ");
}
finally{}
if (a==0 && b==0 && c==0){
result1.setText(" ");
result2.setText(" ");
}
else{
double yy, xx,x1, x2, x3;
double disc = (( b * b) - (4 * a * c));
DecimalFormat fmt = new DecimalFormat("0.###");
if (disc > 0){
double solution1 = ((-1 * b) - Math.sqrt(disc)) / ( 2 * a);
double solution2 = ((-1 * b) + Math.sqrt(disc)) / (2 * a);
result1.setText("Solution #1: " + fmt.format(solution1));
result2.setText("Solution #2: " + fmt.format(solution2));
if (solution1 < solution2){
xStart = solution1 - 5;
xEnd = solution2 + 5;
}
else{
xStart = solution2 - 5;
xEnd = solution1 + 5;
}
}
else if (disc == 0){
double oneSol = (-1 * b) / ( 2 * a);
result1.setText("One Solution: " + fmt.format(oneSol));
result2.setText("");
xStart = oneSol - 5;
xEnd = oneSol + 5;
}
else{
yy = (-1 * b) / (2 * a);
xx = ((b * b) - (4 * a * c));
x1 = Math.abs(xx);
x2 = Math.sqrt(x1);
x3 = (x2) / (2 * a);
result1.setText("Imaginary Solution #1: " + fmt.format(yy) + " - " +
fmt.format(x3)+"i" );
result2.setText("Imaginary Solution #2: " + fmt.format(yy) + " + " +
fmt.format(x3)+"i" );
xStart = (((-1 * b) - (x2)) / ( 2 * a)) - 5;
xEnd = (((-1 * b) + (x2)) / (2 * a)) + 5;
}
}
}
}
and the graph code:
package com.test.quad;
import java.util.ArrayList;
import java.util.List;
import org.achartengine.ChartFactory;
import org.achartengine.chart.PointStyle;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
/**
* Quadratic
*/
public class Graph extends AbstractDemoChart {
/**
* Returns the chart name.
* #return the chart name
*/
public String getName() {
return "Quadratic Functions";
}
/**
* Returns the chart description.
* #return the chart description
*/
public String getDesc() {
return "Quadratic Graph";
}
/**
* Executes the chart demo.
* #param context the context
* #return the built intent
*/
public Intent execute(Context context) {
String[] titles = new String[] { "Function" };
List<double[]> x = new ArrayList<double[]>();
List<double[]> values = new ArrayList<double[]>();
QuadraticActivity c = new QuadraticActivity();
double range = c.xEnd - c.xStart;
double step = .01 * range;
int count = 110;
double xCurrent = c.xStart;
double[] xValueArr = new double[count];
double[] yValueArr = new double[count];
values.add(xValueArr);
values.add(yValueArr);
for (int ii=0; xCurrent <= c.xEnd; xCurrent += step, ii++) {
double yCurrent = (c.a)*Math.pow(xCurrent, 2) + (c.b)*xCurrent + (c.c);
xValueArr[ii] = xCurrent;
yValueArr[ii] = yCurrent;
}
System.out.println(x);
int [] colors = new int[] { Color.BLUE };
PointStyle[] styles = new PointStyle[] { PointStyle.POINT };
XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
setChartSettings(renderer, "Graph of Quadratic Equation", "X", "Y", 0, 360, -1, 1,
Color.GRAY, Color.LTGRAY);
renderer.setXLabels(20);
renderer.setYLabels(10);
return ChartFactory.getLineChartIntent(context, buildDataset(titles, x, values),
renderer);
}
}
Add the the activity GraphicalActivity to the manifest file:
<activity android:name="org.achartengine.GraphicalActivity" />
Related
I create alist method to insert principal values and remaining balances according to the payments.But when I implement this method in actionListner method error occurs(EventDispatchThread Execption).I try to solve it.Please give any help for me to solve this.
public class Loan {
float lamt,irate,inst,lbalance;
int duration,nop;
String amtlist[][] = new String[duration+1][5];
Loan(float lamt, float irate, int duration, int nop) {
this.lamt = lamt;
this.irate = irate;
this.duration = duration;
this.nop = nop;
}
public void alist() {
amtlist[0][0] = "0" ;
amtlist[0][1] = "0";
amtlist[0][2] = "0";
amtlist[0][3] = "0";
amtlist[0][4] = Float.toString(inst*annuity(duration,irate));
float v = 1 / (1 + irate);
for (int i = 1; i < duration + 1; i++) {
amtlist[i][0] = Float.toString(i);
amtlist[i][1] = Float.toString(irate * annuity(duration + 1 - i, irate));
amtlist[i][2] = Float.toString(instalment());
amtlist[i][3] = Double.toString(instalment() * Math.pow(v, i));
amtlist[i][4] = Float.toString(instalment() * annuity(duration - i, irate));
}
}
public float annuity(int duration, float irate) {
float v = 1 / (1 + irate);
float an = (float) ((1 - Math.pow(v, duration)) / irate);
return an;
}
public float instalment(){
return inst = lamt / annuity(duration, irate);
}
public float lbalance() {
return lbalance = inst * annuity(duration - nop, irate);
}
}
public void actionPerformed(ActionEvent e) {
String lamtstr = tf1.getText();
String iratestr = tf2.getText();
String durationstr = tf3.getText();
String nopstr = tf4.getText();
float lamt = Float.parseFloat(lamtstr);
float irate = Float.parseFloat(iratestr);
int duration = Integer.parseInt(durationstr);
int nop = Integer.parseInt(nopstr);
Loan l = new Loan(lamt, irate, duration, nop);
float inst = 0, balance = 0;
if (e.getSource() == b1) {
inst =l.instalment();
balance =l.lbalance();
}
if (e.getSource() == b2) {
l.alist();
fscr.dispose();
new AmTable(l.amtlist);
}
tf5.setText(String.valueOf(inst));
tf6.setText(String.valueOf(balance));
}
I tried solve it by changing alist method to value returning method but my attempt got vain.
if (e.getSource() == b2) {
l.alist();
fscr.dispose();
new AmTable(l.amtlist);
}
I expected to call AmTable function with amlist array.
I'm trying to build an app for fall detection using the accelerometer of a smartphone as a school project (so I still have a lot of things to improve).
I was doing some research and I found this article with some calculations, so I'm trying to turn those into some code.
I asked a friend for some help and he explained me how to do those calculations. But considering it's been a few years since I finished high school and I'm not very good at math, I'm sure I got some stuff wrong.
So I was expecting someone could give me a hand.
Here's what I need and what I have already, in case someone finds any mistake.
return Math.abs(x) + Math.abs(y) + Math.abs(z);
double anX = this.accelerometerValues.get(size -2).get(AccelerometerAxis.X) * this.accelerometerValues.get(size -1).get(AccelerometerAxis.X);
double anY = this.accelerometerValues.get(size -2).get(AccelerometerAxis.Y) * this.accelerometerValues.get(size -1).get(AccelerometerAxis.Y);
double anZ = this.accelerometerValues.get(size -2).get(AccelerometerAxis.Z) * this.accelerometerValues.get(size -1).get(AccelerometerAxis.Z);
double an = anX + anY + anZ;
double anX0 = Math.pow(this.accelerometerValues.get(size -2).get(AccelerometerAxis.X), 2);
double anY0 = Math.pow(this.accelerometerValues.get(size -2).get(AccelerometerAxis.Y), 2);
double anZ0 = Math.pow(this.accelerometerValues.get(size -2).get(AccelerometerAxis.Z), 2);
double an0 = Math.sqrt(anX0 + anY0 + anZ0);
double anX1 = Math.pow(this.accelerometerValues.get(size -1).get(AccelerometerAxis.X), 2);
double anY1 = Math.pow(this.accelerometerValues.get(size -1).get(AccelerometerAxis.Y), 2);
double anZ1 = Math.pow(this.accelerometerValues.get(size -1).get(AccelerometerAxis.Z), 2);
double an1 = Math.sqrt(anX1 + anY1 + anZ1);
double a = an / (an0 * an1);
return (Math.pow(Math.cos(a), -1)) * (180 / Math.PI);
double aX = this.accelerometerValues.get(0).get(AccelerometerAxis.X) * this.accelerometerValues.get(3).get(AccelerometerAxis.X);
double aY = this.accelerometerValues.get(0).get(AccelerometerAxis.Y) * this.accelerometerValues.get(3).get(AccelerometerAxis.Y);
double aZ = this.accelerometerValues.get(0).get(AccelerometerAxis.Z) * this.accelerometerValues.get(3).get(AccelerometerAxis.Z);
double a0 = aX + aY + aZ;
double a1 = (Math.sqrt(Math.pow(aX, 2)) + Math.sqrt(Math.pow(aY, 2)) + Math.sqrt(Math.pow(aZ, 2)));
return (Math.pow(Math.cos(a0 / a1), -1)) * (180 / Math.PI);
I'm getting the same return from the second and the third calculation and neither seems to be the expected result, but I can't find what I'm doing wrong.
Here's the code for the class, for more details
import android.app.IntentService;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import br.com.aimcol.fallalertapp.activity.FallNotificationActivity;
import br.com.aimcol.fallalertapp.model.Elderly;
import br.com.aimcol.fallalertapp.model.Person;
import br.com.aimcol.fallalertapp.model.User;
import br.com.aimcol.fallalertapp.util.AccelerometerAxis;
import br.com.aimcol.fallalertapp.util.RuntimeTypeAdapterFactory;
public class FallDetectionService extends IntentService implements SensorEventListener {
private static final int ACCELEROMETER_SAMPLING_PERIOD = 1000000;
private static final double CSV_THRESHOLD = 23;
private static final double CAV_THRESHOLD = 18;
private static final double CCA_THRESHOLD = 65.5;
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private User user;
private Gson gson;
private Long lastSentInMillis;
private Long minTimeToNotifyAgain = 3000000L;
private List<Map<AccelerometerAxis, Double>> accelerometerValues = new ArrayList<>();
public FallDetectionService() {
super(".FallDetectionService");
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* #param name Used to name the worker thread, important only for debugging.
*/
public FallDetectionService(String name) {
super(name);
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public final void onAccuracyChanged(Sensor sensor,
int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
// Axis of the rotation sample, not normalized yet.
double x = event.values[0];
double y = event.values[1];
double z = event.values[2];
if (this.isFallDetected(x, y, z)) {
if (this.isOkayToNotifyAgain()) {
this.lastSentInMillis = System.currentTimeMillis();
Toast.makeText(this, "Fall", Toast.LENGTH_LONG).show();
FallNotificationActivity.startFallNotificationActivity(this, this.gson.toJson(this.user));
}
}
}
private boolean isFallDetected(double x,
double y,
double z) {
double acceleration = this.calculateAcceleration(x, y, z);// - SensorManager.GRAVITY_EARTH;
this.addAccelerometerValuesToList(x, y, z, acceleration);
String msg = new StringBuilder("x: ").append(x).append(" y: ").append(y).append(" z: ").append(z).append(" acc: ").append(acceleration).toString();
Log.d("FDS-Acc-Values", msg);
if (acceleration > CSV_THRESHOLD) {
// double angleVariation = this.calculateAngleVariation();
// if (angleVariation > CAV_THRESHOLD) {
// double changeInAngle = this.calculateChangeInAngle();
// if (changeInAngle > CCA_THRESHOLD) {
Log.d("FDS-Fall-Happened", msg);
return true;
// }
// }
}
return false;
}
private void addAccelerometerValuesToList(double x,
double y,
double z,
double acceleration) {
if(this.accelerometerValues.size() >= 4) {
this.accelerometerValues.remove(0);
}
Map<AccelerometerAxis, Double> map = new HashMap<>();
map.put(AccelerometerAxis.X, x);
map.put(AccelerometerAxis.Y, y);
map.put(AccelerometerAxis.Z, z);
map.put(AccelerometerAxis.ACCELERATION, acceleration);
this.accelerometerValues.add(map);
}
private double calculateAcceleration(double x,
double y,
double z) {
return Math.abs(x) + Math.abs(y) + Math.abs(z);
}
private double calculateAngleVariation() {
int size = this.accelerometerValues.size();
if (size < 2){
return -1;
}
double anX = this.accelerometerValues.get(size -2).get(AccelerometerAxis.X) * this.accelerometerValues.get(size -1).get(AccelerometerAxis.X);
double anY = this.accelerometerValues.get(size -2).get(AccelerometerAxis.Y) * this.accelerometerValues.get(size -1).get(AccelerometerAxis.Y);
double anZ = this.accelerometerValues.get(size -2).get(AccelerometerAxis.Z) * this.accelerometerValues.get(size -1).get(AccelerometerAxis.Z);
double an = anX + anY + anZ;
// double an = this.accelerometerValues.get(size -2).get(AccelerometerAxis.ACCELERATION) * this.accelerometerValues.get(size -1).get(AccelerometerAxis.ACCELERATION);
double anX0 = Math.pow(this.accelerometerValues.get(size -2).get(AccelerometerAxis.X), 2);
double anY0 = Math.pow(this.accelerometerValues.get(size -2).get(AccelerometerAxis.Y), 2);
double anZ0 = Math.pow(this.accelerometerValues.get(size -2).get(AccelerometerAxis.Z), 2);
double an0 = Math.sqrt(anX0 + anY0 + anZ0);
double anX1 = Math.pow(this.accelerometerValues.get(size -1).get(AccelerometerAxis.X), 2);
double anY1 = Math.pow(this.accelerometerValues.get(size -1).get(AccelerometerAxis.Y), 2);
double anZ1 = Math.pow(this.accelerometerValues.get(size -1).get(AccelerometerAxis.Z), 2);
double an1 = Math.sqrt(anX1 + anY1 + anZ1);
double a = an / (an0 * an1);
return (Math.pow(Math.cos(a), -1)) * (180 / Math.PI); //cosseno inverso? Ou cosseno ^-1?
}
private double calculateChangeInAngle() {
int size = this.accelerometerValues.size();
if (size < 4){
return -1;
}
double aX = this.accelerometerValues.get(0).get(AccelerometerAxis.X) * this.accelerometerValues.get(3).get(AccelerometerAxis.X);
double aY = this.accelerometerValues.get(0).get(AccelerometerAxis.Y) * this.accelerometerValues.get(3).get(AccelerometerAxis.Y);
double aZ = this.accelerometerValues.get(0).get(AccelerometerAxis.Z) * this.accelerometerValues.get(3).get(AccelerometerAxis.Z);
double a0 = aX + aY + aZ;
double a1 = (Math.sqrt(Math.pow(aX, 2)) + Math.sqrt(Math.pow(aY, 2)) + Math.sqrt(Math.pow(aZ, 2)));
return (Math.pow(Math.cos(a0 / a1), -1)) * (180 / Math.PI);
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
if (this.user == null) {
String userJson = intent.getStringExtra(User.USER_JSON);
this.user = this.gson.fromJson(userJson, User.class);
}
}
#Override
public int onStartCommand(Intent intent,
int flags,
int startId) {
if (this.gson == null) {
RuntimeTypeAdapterFactory<Person> runtimeTypeAdapterFactory = RuntimeTypeAdapterFactory
.of(Person.class, "type")
.registerSubtype(Elderly.class, Elderly.class.getSimpleName());
this.gson = new GsonBuilder().registerTypeAdapterFactory(runtimeTypeAdapterFactory).create();
}
if (this.user == null) {
String userJson = intent.getStringExtra(User.USER_JSON);
this.user = this.gson.fromJson(userJson, User.class);
}
this.mSensorManager = (SensorManager) super.getSystemService(Context.SENSOR_SERVICE);
this.mAccelerometer = this.mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if (this.mAccelerometer == null) {
throw new RuntimeException("Acelerometro não encontrado");
}
this.mSensorManager.registerListener(this, this.mAccelerometer, ACCELEROMETER_SAMPLING_PERIOD);
return Service.START_STICKY;
}
private boolean isOkayToNotifyAgain() {
return this.lastSentInMillis == null || (this.lastSentInMillis + this.minTimeToNotifyAgain) < System.currentTimeMillis();
}
public static void startFallDetectionService(String userJson,
Context context) {
Intent fallDetectionServiceIntent = new Intent(context, FallDetectionService.class);
fallDetectionServiceIntent.putExtra(User.USER_JSON, userJson);
context.startService(fallDetectionServiceIntent);
}
#VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
protected boolean testFallDetection(List<Map<AccelerometerAxis, Double>> values) {
for (Map<AccelerometerAxis, Double> value : values) {
if (this.isFallDetected(
value.get(AccelerometerAxis.X),
value.get(AccelerometerAxis.Y),
value.get(AccelerometerAxis.Z))) {
return true;
}
}
return false;
}
}
Ps: Sorry if I got something wrong. English is not my first language and I'm a little rusty.
Ps2: Sorry about my variable names.
Ps3: The code is on github, if you want to take a look on the rest of the code or if instead of posting a reply here you want to make a pull request or something, feel free.
This question might not be appropriate here. SO isn't intended as a code review site.
Here are a few comments to consider:
The first formula you list is not what you've expressed in code. There is no square root or sum of squares in the formula, but you put them into code for some reason. The article says SV should be the sum of the absolute value of the components of the linear acceleration vector. That's not what your code says.
The meaning of n and n+1 in the second formula isn't clear to me. Are those consecutive time points? The dot product of two vectors is easy to calculate - but for which two vectors?
The third formula calls for an average of acceleration vectors over a four second window. I don't see that being done anywhere. The number of vectors involved in the average would depend on your sampling rate.
I would suggest that you re-read the article several more times.
I'd also advise that you encapsulate these into functions and write some good unit tests for them. See if you can reproduce the results from the paper.
I am implementing hybrid image with ImageJ and stuck at merging low filter image and high filter image to form a hybrid image.
This is what I already done.I have 2 images from Gaussian Blur and Laplician of Gaussian filer. I need to merge these 2 images by layer after that. Any idea how to achieve it?
import ij.*;
import ij.process.*;
import ij.gui.*;
import java.awt.*;
import ij.plugin.filter.*;
import ij.plugin.*;
import ij.io.*;
import java.io.*;
public class HybridImage_Plugin implements PlugInFilter{
int cfsize=3;
String img_lowPass;
String img_highPass;
private double[][] filter;
private double sigma;
float w=2 ,delta=0 , thr=0;
int mode=0;
//dialogbox
private boolean GUI()
{
GenericDialog gd = new GenericDialog("Enter Values", IJ.getInstance());
gd.addNumericField("Sigma (3,5,9,17,35)", cfsize, 0);
gd.addStringField("Low-Pass", "/home/atrx/ImageJ/plugins/hybridimage/l1.tif");
gd.addStringField("High-Pass", "/home/atrx/ImageJ/plugins/hybridimage/l2.tif");
return getUserParams(gd);
}
//get parameters
private boolean getUserParams(GenericDialog gd)
{
gd.showDialog();
if (gd.wasCanceled())
{
return false;
}
cfsize = (int) gd.getNextNumber();
img_lowPass = gd.getNextString();
img_highPass= gd.getNextString();
return true;
}
public int setup(String arg, ImagePlus imp) {
return PlugInFilter.NO_IMAGE_REQUIRED;
}
public void run(ImageProcessor ip) {
int[][] result;
if(GUI() == false)
{
return;
}
else
{
Opener opener1 = new Opener();
Opener opener2 = new Opener();
ImagePlus imp1= opener1.openImage(img_lowPass);
ImagePlus imp2= opener2.openImage(img_highPass);
//imp1.show("Low Pass Image");
//imp2.show("HighPass Image");
ImageProcessor ip1 = imp1.getProcessor();
ImageProcessor ip2 = imp2.getProcessor();
//lowpass filter(Gaussian Blur)
ip1.blurGaussian(cfsize);
showProcessor(ip1,"Low Pass Filtered Image");
//highpass filter(LoG)
int csize = ip2.getHeight();
int rsize = ip2.getWidth();
Rectangle rect = ip2.getRoi();
int d0,a0,acr,dow,it;
int i,x,y;
double h12, h21, ft, h1h2, h2h1, fmu, dh, dv;
double r, dt, dmx, dmn;
float logaus[] = new float[(rect.width>rect.height)? rect.width : rect.height];
float gaus[] = new float[(rect.width>rect.height)? rect.width : rect.height];
float dgaus[] = new float[(rect.width>rect.height)? rect.width : rect.height];
long zcn =0;
byte pixels[] = (byte[])ip2.getPixels();
int img_in[] = new int[rect.width*rect.height];
if (cfsize<0) cfsize=3;
if (cfsize>35) cfsize=35;
if(w<0) w=0;
int fsize = (int)(cfsize*w);
if (fsize%2 == 0)
{
fsize += 1;
}
double dimg[] = new double[rect.height*rect.width];
double dr[] = new double[rect.height*rect.width];
i=0;
for(y=rect.y;y<(rect.y+rect.height);y++)
{
for(x=rect.x;x<(rect.x+rect.width);x++)
{
img_in[i] = (pixels[(y*rsize)+x]&0xff);
i++;
}
}
int size = rect.width + fsize -1;
int image[] = new int[(rect.width+fsize-1)*(rect.height+fsize-1)];
int extension= (fsize/2);
for( i=0; i<rect.height;i++)
{
System.arraycopy(img_in,(i*rect.width),image,( ((i+extension)*(rect.width+fsize-1))+ extension ),rect.width);
}
h1h2= h2h1 = h12 =0.0;
for(i=1; i<( (fsize+1) /2);i++)
{
w = (float)cfsize/(float)2.0/(float)1.414;
ft = i/w;
gaus[i] = (float)Math.exp(-ft*ft/2);
h1h2 += 2.0 *(gaus[i]);
logaus[i] =(float)(1-ft*ft)*(float)Math.exp(-ft*ft/2);
h2h1 += 2.0*(logaus[i]);
dgaus[i] =(float)ft*(float)Math.exp(-ft*ft/2);
}
fmu = (h2h1 + 1)* (h1h2+1);
int prel[] = new int[rect.width+1];
dmx = -99999.9;
dmn = 99999.9;
int limit = ((rect.width+fsize-1)*(rect.height+fsize-1));
for(d0=0;d0<rect.height;d0++)
{
for(a0=0;a0<rect.width;a0++)
{
acr = a0 + fsize/2;
dow = d0 + fsize/2;
dh = dv = 0.0;
h1h2 = h2h1 = 0.0;
for (int j=1; j<(fsize+1)/2; j++)
{
int a0d0, a0d1, a1d0, a1d1;
h12=h21=0.0;
for(i=1;i<(fsize+1)/2;i++)
{
a0d0 = acr-i+((dow-j)*size);
a0d1 = acr-i+((dow+j)*size);
a1d0 = acr+i+((dow-j)*size);
a1d1 = acr+i+((dow+j)*size);
h12 += logaus[i]*(image[a0d0] + image[a0d1]+
image[a1d0] + image[a1d1]);
h21 += gaus[i]* (image[a0d0] + image[a0d1] +
image[a1d0] + image[a1d1]);
}
a0d0 = acr-j+dow*size;
a0d1 = acr+(dow-j)*size;
a1d0 = acr+j+dow*size;
a1d1 = acr+(dow+j)*size;
h1h2 += gaus[j] * (h12+ image[a0d0]+image[a0d1]+
image[a1d0]+image[a1d1]);
h2h1 += logaus[j]*(h21+ image[a0d0]+ image[a0d1] +
image[a1d0] + image[a1d1] );
if(thr != 0.0)
{
dh += dgaus[j] * ( image[a1d0] - image[a0d0] );
dv += dgaus[j] * ( image[a1d1] - image[a0d1] );
}
}
dt = dimg[d0*rect.width+a0] = h1h2 + h2h1 + (2*image[dow*size+acr]) ;
if (dt > dmx) dmx = dt;
if (dt < dmn) dmn = dt;
if( thr!= 0.0)
{
dr[(d0*rect.width)+a0] = Math.abs(dh) + Math.abs(dv);
}
}
}
dmx = (dmx-dmn) / 2;
dmn += dmx;
int row=0, column=0;
for(d0=0;d0<rect.height;d0++)
{
for(a0=0;a0<rect.width;a0++)
{
int id = (d0*rect.width) +a0;
int index = rsize*(rect.y+d0) + (a0+rect.x);
int k = 15;
it = (int)(dt = (dimg[id] - (dmn-delta*dmx))*255 / (dmx*(1+Math.abs(delta))));
switch(mode){
case 0:
pixels[index] = (byte)((dt-dmn+dmx)/dmx*127);
break;
case 1:
pixels[index] = (byte)Math.abs(it);
break;
case 2:
pixels[index] = (byte)( ((dt!=0)?((dt>0) ? 1: -1) : 0) * 192);
break;
case 3:
default:
r = dr[id];
it = ( (dt!=0) ? ((dt>0) ? 1: -1) : 0);
if( it==0 && r>=thr)
{
k = 255;
zcn++;
}
else
{
if( (it*prel[a0]<0 || it*prel[a0+1]<0) && r>=thr)
{
k = 255;
zcn++;
}
}
prel[a0+1] = it;
if(k==255 || mode!=3)
pixels[index] = (byte)k;
break;
}
}
}
showProcessor(ip2,"High Pass Filtered Image");
}
}
static void showProcessor(ImageProcessor ip, String title){
ImagePlus win = new ImagePlus(title,ip);
win.show();
}
}
Have you tried performing a weighted sum?
OUT = w*LPF + (1 - w)*HPF
This kind of sum is used everywhere. In particular, image blending, alpha matting and even in some optimization schemes.
However because there are patches of varying spatial frequencies all around your image, you may have to make the weight adaptive. You also have to choose which one you want to emphasize more. Do you want the low pass or high pass information to stand out more? Depending on which you want, you might want to use information in either one of those images and run it through some distance or similarity measure to get the right weight.
I'm using some code from my university's lecturer for a new project and everything seems to be working except for that one little piece, where I want to import "data.Frame" and I just don't know what's missing so my code would function. If anyone knows the solution or could give me an alternative so I could import the needed "Frame" - would be awesome!
I'm using eclipse!
The code is:
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import data.Frame; // HERE IS THE PROBLEM!
/**
* Compares the annotations of two or more annotators and groups them together,
* before they are written to a csv file.
*/
public class ComparisonWriter
{
private String content;
private final int A1 = 1;
private final int A2 = 2;
private final int A3 = 3;
// private final int A4 = 4;
private int numberOfAnnotators = 3;
String outputFileName = "data/200Saetze/Gruppe 1/comparison_buchpreis2_alle.csv";
String inputA1 = "data/200Saetze/Gruppe 1/Daniela/buchpreis2.xml";
String inputA2 = "data/200Saetze/Gruppe 1/Inga/buchpreis2.xml";
String inputA3 = "data/200Saetze/Gruppe 1/Stefan/buchpreis2.xml";
public ComparisonWriter()
{
content = "SatzID;Annotator;Frame;SE;exact;partial;Source;Annotator;SourceString;" +
"exact;exact ohne leer;exact ohne leer (SE);partial;koreferent;SourceFlag;exact;Target;Annotator;" +
"TargetString;exact;exact ohne leer;exact ohne leer (SE);partial;koreferent;TargetFlag;;FrameFlag";
AnnotationReader annotationReaderA1 = new AnnotationReader(inputA1);
Map<String, List<Frame>> seAnnotator1 = annotationReaderA1.getAllSubjectiveExpressions();
AnnotationReader annotationReaderA2 = new AnnotationReader(inputA2);
Map<String, List<Frame>> seAnnotator2 = annotationReaderA2.getAllSubjectiveExpressions();
AnnotationReader annotationReaderA3 = new AnnotationReader(inputA3);
Map<String, List<Frame>> seAnnotator3 = annotationReaderA3.getAllSubjectiveExpressions();
Set<String> sentences = seAnnotator1.keySet();
for (String sentence : sentences)
{
//add leading zeros
content += "\n\n" + sentence + ";" + annotationReaderA1.sentenceStrings.get(sentence);
//add the annotations in a sorted order
Map<Integer, List<Frame>> allFramesInSentence = new HashMap<Integer, List<Frame>>();
allFramesInSentence.put(A1, seAnnotator1.get(sentence));
allFramesInSentence.put(A2, seAnnotator2.get(sentence));
allFramesInSentence.put(A3, seAnnotator3.get(sentence));
// allFramesInSentence.put(A4, seAnnotator4.get(sentence));
//
//get the one with the most annotations
int largest = getIndexOfLargestList(allFramesInSentence);
if(largest == 0)
continue;
for (int i = 0; i < allFramesInSentence.get(largest).size(); i++)
{
Frame frame = allFramesInSentence.get(largest).get(i);
content += "\n\n;A" + largest + ";" + frame;
frame.setConsidered(true);
findOverlappingAnnotations(allFramesInSentence, largest, frame);
}
//Check, if there are not considered annotations in one of the frame lists for that sentence.
for (int a = 1; a <= 4; a++)
{
List<Frame> frameList = allFramesInSentence.get(a);
if(a != largest && frameList != null)
{
for (Frame frame : frameList)
{
if(frame.isConsidered() == false)
{
content += "\n\n;A" + a + ";" + frame;
frame.setConsidered(true);
findOverlappingAnnotations(allFramesInSentence, a, frame);
}
}
}
}
}
writeContentToFile(content, outputFileName, false);
}
/**
* Find overlapping annotations.
* #param frames - list of frames, potentially overlapping with the given one.
* #param largest
* #param frame - frame in question.
*/
private void findOverlappingAnnotations(Map<Integer, List<Frame>> frames,
int largest, Frame frame)
{
for (int a = 1; a <= 4; a++)
{
//If j is not the current largest frame list and there are annotated frames
//in from this annotator (a)
if(a != largest && frames.get(a) != null)
{
for (Frame compareFrame : frames.get(a))
{
addOverlappingAnnotations2Conent(frame, a, compareFrame);
}
}
}
}
/**
* Add overlapping Annotations (measured by matching ids) to the content attribute.
* #param frame
* #param a - Annotator index
* #param compareFrame
*/
private void addOverlappingAnnotations2Conent(Frame frame, int a,
Frame compareFrame)
{
List<String> terminalIDs = compareFrame.getTerminalIDs();
for (String id : terminalIDs)
{
if(compareFrame.isConsidered())
break;
if(frame.getTerminalIDs().contains(id))
{
//Write it to the content
content += "\n;A" + a + ";" + compareFrame;
compareFrame.setConsidered(true);
break;
}
}
}
/**
* Get the index of the largest frame list in the map.
* #param frames - a map with all the frames for each annotator (key: annotator)
* #return The index of the largest frame list.
*/
private int getIndexOfLargestList(Map<Integer, List<Frame>> frames)
{
int size = 0;
int largest = 0;
for(int a = 0; a <= numberOfAnnotators; a++)
{
if(frames.get(a) != null)
{
if(frames.get(a).size() > size)
largest = a;
}
}
return largest;
}
You basically need Frame class in your classpath. If you have this class in some jar, then add that jar to your classpath.
You need to get a copy of the source code or class file for the Frame class and add it to your project. The source code should be in a file called Frame.java.
This is a program from OpenCV ColorBlobDetectionActivity.java sample, and I tried to modify it so that it would detect yellow objects when the screen is touched, but it always detects black object only even though I specified the color Scalar to be yellow. I have put comments of "NOTICE" in the places where I think would be relevant.
package com.example.road_guiding;
import java.util.List;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class ColorBlobDetectionActivity extends Activity implements View.OnTouchListener, CameraBridgeViewBase.CvCameraViewListener2 {
// private static final String TAG = "OCVSample::Activity";
private Scalar CONTOUR_COLOR;
private Scalar mBlobColorHsv;
private Scalar mBlobColorRgba;
//NOTICE
private Scalar temp;
private ColorBlobDetector mDetector;
private boolean mIsColorSelected = false;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
public void onManagerConnected(int paramAnonymousInt) {
switch (paramAnonymousInt) {
default:
super.onManagerConnected(paramAnonymousInt);
// Log.i("OCVSample::Activity", "OpenCV loaded successfully");
ColorBlobDetectionActivity.this.mOpenCvCameraView.enableView();
ColorBlobDetectionActivity.this.mOpenCvCameraView.setOnTouchListener(ColorBlobDetectionActivity.this);
return;
}
}
};
private CameraBridgeViewBase mOpenCvCameraView;
private Mat mRgba;
// private Size SPECTRUM_SIZE;
// private Mat mSpectrum;
public ColorBlobDetectionActivity() {
Log.i("OCVSample::Activity", "Instantiated new " + getClass());
}
private Scalar converScalarHsv2Rgba(Scalar paramScalar) {
Mat localMat = new Mat();
Imgproc.cvtColor(new Mat(1, 1, CvType.CV_8UC3, paramScalar), localMat, 71, 4);
return new Scalar(localMat.get(0, 0));
}
public Mat onCameraFrame( CameraBridgeViewBase.CvCameraViewFrame paramCvCameraViewFrame) {
this.mRgba = paramCvCameraViewFrame.rgba(); // mRbga = input frame with color
if (this.mIsColorSelected) {
this.mDetector.process(this.mRgba);
//contour info is ready in detector
List colorContour = this.mDetector.getContours();
// Log.e("OCVSample::Activity", "Contours count: " + localList.size());
Imgproc.drawContours(this.mRgba, colorContour, -1, this.CONTOUR_COLOR); //draw contour around detected area
this.mRgba.submat(4, 68, 4, 68).setTo(this.mBlobColorRgba);
// Producing spectrum
// Mat localMat = this.mRgba.submat(4, 4 + this.mSpectrum.rows(), 70, 70 + this.mSpectrum.cols());
// this.mSpectrum.copyTo(localMat);
}
return this.mRgba;
}
public void onCameraViewStarted(int paramInt1, int paramInt2) {
this.mRgba = new Mat(paramInt2, paramInt1, CvType.CV_8UC4); //width - - the width of the frames that will be delivered
this.mDetector = new ColorBlobDetector();
this.mBlobColorRgba = new Scalar(255.0);
this.mBlobColorHsv = new Scalar(255.0);
this.CONTOUR_COLOR = new Scalar(255.0, 0.0, 0.0, 255.0); //Specfiy the color of contour
//NOTICE
this.temp = new Scalar (237.0, 169.0, 50.0, 255.0);
//yellow to be used:
// this.mBlobColorRgba.val[0] = 237;
// this.mBlobColorRgba.val[1] = 169;
// this.mBlobColorRgba.val[2] = 50;
// this.mBlobColorRgba.val[3] = 255;
// this.mSpectrum = new Mat();
// this.SPECTRUM_SIZE = new Size(200.0, 64.0);
}
public void onCreate(Bundle paramBundle) {
// Log.i("OCVSample::Activity", "called onCreate");
super.onCreate(paramBundle);
// requestWindowFeature(1); // do not show app title
// getWindow().addFlags(128);
setContentView(R.layout.activity_color_blob_detection);
this.mOpenCvCameraView = ((CameraBridgeViewBase) findViewById(R.id.HelloOpenCvView));
this.mOpenCvCameraView.setCvCameraViewListener(this);
}
public boolean onTouch(View paramView, MotionEvent paramMotionEvent)
{
int cameraViewWidth = this.mRgba.cols(); // cameraViewWidth = i
int cameraViewHeight = this.mRgba.rows(); // cameraViewHeight = j
int xOffset = (this.mOpenCvCameraView.getWidth() - cameraViewWidth) / 2;
int yOffset = (this.mOpenCvCameraView.getHeight() - cameraViewHeight) / 2;
int touchX = (int)paramMotionEvent.getX() - xOffset;
int touchY = (int)paramMotionEvent.getY() - yOffset;
// Log.i("OCVSample::Activity", "Touch image coordinates: (" + n = touchX + ", " + i1=touchY + ")");
if ((touchX < 0) || (touchY < 0) || (touchX > cameraViewWidth) || (touchY > cameraViewHeight)) {
return false;
}
Rect touchedRect = new Rect();
if (touchX > 4) {
touchedRect.x = touchX - 4;
touchedRect.y = touchY - 4;
touchedRect.width = touchX + 4 - touchedRect.x;
}
for (int i5 = touchY + 4 - touchedRect.y;; i5 = cameraViewHeight - touchedRect.y) {
touchedRect.height = i5;
// Mat touchedRegionRgba = this.mRgba.submat(touchedRect);
Mat touchedRegionRgba = new Mat();
//NOTICE
Imgproc.cvtColor(new Mat(1, 1, CvType.CV_8UC3, temp), touchedRegionRgba, 71, 0);
Mat touchedRegionHsv = new Mat();
Imgproc.cvtColor(touchedRegionRgba, touchedRegionHsv, Imgproc.COLOR_RGB2HSV_FULL); //67
this.mBlobColorHsv = Core.sumElems(touchedRegionHsv); //calculate average color of touched region
int pixelCount = touchedRect.width * touchedRect.height;
for (int i = 0; i < this.mBlobColorHsv.val.length; i++) {
double[] arrayOfDouble = this.mBlobColorHsv.val;
arrayOfDouble[i] /= pixelCount;
}
touchedRegionRgba.release();
touchedRegionHsv.release();
break;
}
this.mBlobColorRgba = converScalarHsv2Rgba(this.mBlobColorHsv);
// Log.i("OCVSample::Activity", "Touched rgba color: (" + this.mBlobColorRgba.val[0] + ", " + this.mBlobColorRgba.val[1] + ", " + this.mBlobColorRgba.val[2] + ", " + this.mBlobColorRgba.val[3] + ")");
this.mDetector.setHsvColor(this.mBlobColorHsv);
// Imgproc.resize(this.mDetector.getSpectrum(), this.mSpectrum, this.SPECTRUM_SIZE);
this.mIsColorSelected = true;
return false;
}
public void onDestroy() {
super.onDestroy();
if (this.mOpenCvCameraView != null) {
this.mOpenCvCameraView.disableView();
}
}
public void onPause() {
super.onPause();
if (this.mOpenCvCameraView != null) {
this.mOpenCvCameraView.disableView();
}
}
public void onResume() {
super.onResume();
OpenCVLoader.initAsync("2.4.3", this, this.mLoaderCallback);
}
public void onCameraViewStopped() {
this.mRgba.release();
}
}
Any help would be appreciated, thanks!
Sorry i don't know Java but i can suggest the general logic to detect "Yellow" color. You should convert the RGB image into YUV image and then equalize the Y-channel. As Y-channel is for luminance, so you reduce the effects of illumination changes by doing so.
-Then convert back your image to RGB from YUV
-Convert the image to HSV now.
-Now try to calculate only those pixels which possibly represent "Yellow" color. For that, use the following conditions:
The pixel should have S>0 (or some other value near to 0) to eliminate the white pixels which create problem in the caculation.
The pixel should have V>0 to remove the "Black pixels" which have V=0
If the H> 22 && H<37 then increase the yellowPixelCount by 1.
-So, by following the above mentioned procedure, you can count the "yellow" pixels in the image. And, if the count is greater than the threshold then you can predict that it is "yellow" color.
PS: Don't forget to count the total number of pixel which fullfill the criteria 1 & 2 so that you can use that value to find the percentage of yellow component to predict whether the image has yellow color or not.
if (condition 1 & 2 satisfied)
{
totalPixelCount++;
if(condition 3 satisfied)
{
yellowPixelCount
}
}
% of yellow componet = yellowPixelCount/totalPixelCount*100