Find the next double value in an array - java

I'm programming a simulation of a Radio Tuner. Now I want to have a method that can loop through an array or arraylist, by steps of 0.05MHz. At the moment I have a array with my favorite radio frequencies, and the loop has to be stop if a frequency is found.
public static double favFrequencies [] = {89.8, 91.5, 93.7, 95.1, 97.7, 99.2, 100.7, 101.2, 101.7, 102.7, 103.0, 104.4};
At the moment I have the following code:
public static void searchDown()
{
double startFrequency = Math.round(currentFreq * 100);
double maxFrequency = Math.round(87.80 * 100);
for (double f = startFrequency; f > maxFrequency; f -= 5) {
//boolean nextFavFound = false;
if (f < 8785)
{
f = 10800;
}
for (double f2 : favFrequencies) {
if (f / 100 == f2) {
nextFavFound = true;
//break;
}
}
if (nextFavFound) {
currentFreq = f /100;
RadioGUI.lblFreq.setText("FM " + Double.toString(currentFreq)+ "Mhz");
System.out.println("next favFrequency: " + f / 100);
nextFavFound = false;
break;
}
}
}
It does work quite well, but when I run the method again, it will not work with the new outputted value of the first time.

You will run into precision problems when using for-loops and an double increment with decimal places. One pragmatic approach for your problem would be multiplying by a factor of 100.
public static void main(String[] args) {
double startFrequency = Math.round(88 * 100);
double maxFrequency = Math.round(108 * 100);
for (double f = startFrequency; f < maxFrequency; f += 5) {
boolean nextFavFound = false;
for (double f2 : favFrequencies) {
if (f / 100 == f2) {
nextFavFound = true;
break;
}
}
if (nextFavFound) {
System.out.println("next favFrequency: " + f / 100);
}
}
}

Start with a simple for loop, initiate i at whatever the minimum frequency is, stop at the max frequency and increment by 0.05 (make sure i is a double). Then, you can check at each step:
boolean containsFav = false;
for(double i=80.00;i<110.00;i=i+0.05){
if(Arrays.asList(favFrequencies).contains(i)){
containsFav = true;
break;
}
}

With the following code I fixed my problem.
public static void searchUp()
{
currentFreq +=0.05;
double startFrequency = Math.round(currentFreq * 100);
double maxFrequency = Math.round(108 * 100);
for (double f = startFrequency; f < maxFrequency; f += 5) {
//boolean nextFavFound = false;
if (f > 10790)
{
f = 8780;
}
for (double f2 : favFrequencies) {
if (f / 100 == f2) {
nextFavFound = true;
//break;
}
}
if (nextFavFound) {
currentFreq = f /100;
RadioGUI.lblFreq.setText("FM " + Double.toString(currentFreq)+ "Mhz");
//System.out.println("next favFrequency: " + f / 100);
nextFavFound = false;
//currentFreq +=0.05;
break;
}
}
}

Related

EventDispatchThread Execption

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.

Multithread increases calculation time - Java

I was asked to check calculation time depending on number of threads working on the problem. Therefore I had written a program that calculates integral using Monte Carlo method. I am dividing the range for number of threads. After that I stats threads, which calculate their part, and finally sum partial results to get general one.
The problem is that time of calculation increases with number of threads instead of decreasing (i7 processor, Windows 7)
A few people working on it, and we do not know why is that. I hope someone will give me an advice.
I attach code:
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentLinkedQueue;
public class Runner {
private static final int MAXT = 10; // maksymalna ilość wątków
static PrintWriter outM;
static PrintWriter outMTime;
public static void main(String[] args){
double xp = 2;
double xk = 3;
filesOp();
// Wypisywanie kolumn tabeli
for(int threadNumber=1; threadNumber<=MAXT; threadNumber++){
outM.print("\t"+ threadNumber);
outMTime.print("\t"+ threadNumber);
}
double time1;
double time2;
//double startTime=System.currentTimeMillis(); // Przed wystartowaniem programu
for(int n=10000; n<=10000000; n=n*10){
System.out.println("Licze dla: " + n + " punktow.");
outM.print("\n"+n);
outMTime.print("\n"+n);
for(int threadNumber=1; threadNumber<=MAXT; threadNumber++){
outM.print("\t");
outMTime.print("\t");
time1=System.nanoTime();
multiThread(xp, xk, n, threadNumber);
time2=System.nanoTime();
outMTime.print((time2-time1)/1000000);
// czas pracy dla danej liczby wątków
}
}
outM.close();
outMTime.close();
}
public static void multiThread(double xp, double xk, int n, int threadNumber){
// Funkcja licząca całkę wielowątkowo.
// Całka do policzenia jest dzielona pomiędzy wątki
ArrayList<Thread> threadList = new ArrayList<Thread>();
ConcurrentLinkedQueue<Double> results = new ConcurrentLinkedQueue<Double>();
for(int i=0; i<threadNumber; i++){
MonteCarlo mc = new MonteCarlo( xp+(i*((xk-xp)/threadNumber)), xp+((i+1)*((xk-xp)/threadNumber)), (int)(n/threadNumber), results);
Thread t = new Thread(mc);
threadList.add(t);
t.start();
}
//for(int j=0; j<threadNumber; j++){ // pętla czeka na zakończenie wątków
for(Thread t : threadList){
try {
//while(t.isAlive()){}
//threadList.get(j).join();
t.join();
} catch (Exception e) {
e.printStackTrace();
}
}
double wynik = 0;
//for(int k=0; k<results.size(); k++){
for(double r: results){
//wynik = wynik + results.remove();
wynik= wynik + r;
}
outM.print(wynik);
}
public static void filesOp(){
File fileTemp;
fileTemp = new File("wyniki.txt");
if (fileTemp.exists()) fileTemp.delete();
fileTemp = new File("pomiary.txt");
if (fileTemp.exists()) fileTemp.delete();
try {
outM = new PrintWriter(new FileWriter("wyniki.txt", true));
outMTime = new PrintWriter(new FileWriter("pomiary.txt", true));
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class MonteCarlo implements Runnable{
double xp;
double xk;
long n;
ConcurrentLinkedQueue<Double> results;
MonteCarlo(double xp, double xk, long n, ConcurrentLinkedQueue<Double> results){
this.xp=xp;
this.xk=xk;
this.n=n;
this.results=results;
}
//funkcja dla ktorej obliczamy calke
private static double func(double x) {
return x*x+3;
}
private static double funcIn(double x, double y) {
if (( y > 0) && (y <= func(x)))
return 1;
else if (( y > 0) && (y <= func(x)))
return -1;
return 0;
}
//random number from a to b
private static double randomPoint(double a, double b) {
return a + Math.random() * (b-a);
}
public void run(){
double yp, yk, calka;
int pointsIn;
yp = 0;
yk = Math.ceil(Math.max(func(xp), func(xk)));
pointsIn = 0;
for (long i=0; i<n; i++) {
pointsIn += funcIn(randomPoint(xp, xk), randomPoint(yp, yk));
}
calka = (pointsIn / (double)n) * ((xk-xp) * (yk-yp));
results.add(calka);
}
}
And the example of results:
1 2 3 4 5 6 7 8 9 10
10000 6.185818 2.821405 3.721287 3.470309 4.068365 3.604195 4.323075 4.192455 6.159694 4.239105
100000 10.994522 15.874134 34.992323 40.851124 36.199631 49.54579 45.122417 61.427132 55.845435 60.7661
1000000 108.653008 274.443662 340.274574 407.054352 437.455361 469.853467 496.849012 584.519687 571.09329 594.152023
10000000 1066.059033 2877.947652 3600.551966 4175.707089 4488.434247 5081.572093 5501.217804 6374.335759 6128.274553 6339.043475
The problem most likely lies in
private static double randomPoint(double a, double b) {
return a + Math.random() * (b-a);
}
Math.random() performs poorly under heavy contention. If you are using java 7 or later, try this instead:
private static double randomPoint(double a, double b) {
return ThreadLocalRandom.current().nextDouble(a, b);
}
Using static funtions frequently is one of the pitfalls in Multithreading.
A more general answer can be found in this post already.

Validate routing number

How to validate bank routing number in java ?
can any one help me out.
for example
void boolean validate(String str){
// some code
return true; //if valid otherwise return false
}
Please find who needs a routing number validator.
routing-number.validator.ts
import { AbstractControl, ValidationErrors } from '#angular/forms';
export const routingNumberValidator = (): ((AbstractControl) => ValidationErrors | null) => {
return (control: AbstractControl): ValidationErrors | null => {
const targetValue = control.value;
if (!targetValue) {
return null;
}
const digits = targetValue.split('').map(d => parseInt(d, 10));
const checksum = 3 * (digits[0] + digits[3] + digits[6]) + 7 * (digits[1] + digits[4] + digits[7]) + (digits[2] + digits[5] + digits[8]);
return (checksum % 10 === 0) ? null : { routingnumber: true };
};
};
In your yourComponent.component.ts:
this.yourForm = this.fb.group({
routingNumber: [null, Validators.compose([
Validators.required,
routingNumberValidator()
])]
});
And in your yourComponent.component.html:
<nz-form-control [nzErrorTip]="routingNumberErrorTemplate">
<input
nz-input
formControlName="routingNumber"
id="routingNumber">
</nz-form-control>
<ng-template
#routingNumberErrorTemplate
let-control>
<span data-cy="routing-number-input-error">
<ng-container *ngIf="control.hasError('required')">The routing number is required</ng-container>
<ng-container *ngIf="control.hasError('routingnumber')">The routing number is invalid</ng-container>
</span>
</ng-template>
I got the solution. Bank Routing Number is validate by using this simple method.
public boolean validateRoutingNumber(String s) {
int checksum=0, len=0, sum=0, mod = 0;
len = s.length();
if(len != 9){
return false;
}else {
String newString = s.substring(s.length()-1);
checksum = Integer.parseInt(newString);
sum = (7*(Integer.parseInt(""+s.charAt(0))+Integer.parseInt(""+s.charAt(3))+ Integer.parseInt(""+s.charAt(6)))) +
(3*(Integer.parseInt(""+s.charAt(1))+Integer.parseInt(""+s.charAt(4))+ Integer.parseInt(""+s.charAt(7))))+
(9*(Integer.parseInt(""+s.charAt(2))+Integer.parseInt(""+s.charAt(5))));
mod = sum % 10;
if(mod == checksum)
return true;
else
return false;
}
}
Just for fun, I wrote a Angular js directive for doing this same thing:
angular.module('ldPortal.directives')
.directive('routingnumber', function(){
return {
// only use as an attribute
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attr, ctrl){
var regex = new RegExp('^[0-9]{9}$','');
var num_at = function(str, index){
try {
return parseInt(str.charAt(index))
}catch (execption){
console.write(execption);
}
};
var validate = function(value){
if(! (value)){
return false;
}
var strVal = value.toString();
if (!regex.test(strVal)){
return false;
}
var checksum = parseInt(strVal.substr(strVal.length-1));
var sum = 0;
sum += 7 * (num_at(strVal, 0)+num_at(strVal, 3)+num_at(strVal,6));
sum += 3 * (num_at(strVal, 1)+num_at(strVal, 4)+num_at(strVal, 7));
sum += 9 * (num_at(strVal, 2)+num_at(strVal, 5));
var mod = sum % 10;
return checksum == mod;
};
ctrl.$parsers.push(function(value){
var is_valid = validate(value);
ctrl.$setValidity('routingnumber', is_valid);
return is_valid ? value : undefined;
});
ctrl.$formatters.push(function(value){
var is_valid = validate(value);
ctrl.$setValidity('routingnumber', is_valid);
return value;
});
}
};
});
I created a simple Routing Validator, hope this works.
RoutingNumberValidator:
import static java.lang.Character.getNumericValue;
public static class RoutingNumberValidator {
public boolean isValid(String value) {
boolean isValid = value != null && value.matches("[0-9]{9}");
if (isValid) {
int check = 0;
for ( int index = 0; index < 3; index++ ) {
int pos = index * 3;
check += getNumericValue(value.charAt(pos)) * 3;
check += getNumericValue(value.charAt(pos + 1)) * 7;
check += getNumericValue(value.charAt(pos + 2));
}
isValid = check != 0 && check % 10 == 0;
}
return isValid;
}
}
RoutingNumberValidatorTest:
public class RoutingNumberValidatorTest {
private List<String> validRoutingNumbers = Arrays.asList("122105155", "082000549");
private List<String> invalidRoutingNumbers = Arrays.asList("1232101155", "032000549");
#Test
public void isValid() throws Exception {
RoutingNumberValidator routingNumberValidator = new RoutingNumberValidator();
validRoutingNumbers.forEach(it-> assertThat(routingNumberValidator.isValid(it)).as("Invalid Routing Number should not be valid %s", it).isTrue());
invalidRoutingNumbers.forEach(it-> assertThat(routingNumberValidator.isValid(it)).as("Invalid Routing Number should not be valid %s", it).isFalse());
}
}
I know this question is old and is already answered many times, but this answer from BrainJar is quite concise and works perfectly. So I thought I'd share.
validateRoutingNumber(num: string) {
// Run through each digit and calculate the total.
let n = 0;
for (let i = 0; i < num.length; i += 3) {
n += parseInt(num.charAt(i), 10) * 3
+ parseInt(num.charAt(i + 1), 10) * 7
+ parseInt(num.charAt(i + 2), 10);
}
// If the resulting sum is an even multiple of ten (but not zero),
// the aba routing number is good.
if (n != 0 && n % 10 == 0) {
return true;
} else {
return false;
}
}
and here is for python:
def validate_routing_number(routing_number):
# quick easy validations
if routing_number is None or routing_number == '':
return False
invalid_routing_message = 'invalid routing number'
if not re.match(r'^[0-9]{9}$', routing_number):
return False
# here is the more complicated validation!
checksum = int(routing_number[-1]) # last digit
sum = 0 # http://en.wikipedia.org/wiki/Routing_transit_number
sum += 7 * (int(routing_number[0])+int(routing_number[3])+int(routing_number[6]))
sum += 3 * (int(routing_number[1])+int(routing_number[4])+int(routing_number[7]))
sum += 9 * (int(routing_number[2])+int(routing_number[5]))
mod = sum % 10
return checksum != mod
package RoutingNumberAlgo;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int checksum = 0, len = 0, sum = 0, mod = 0, rem = 0;
Scanner ss = new Scanner(System.in);
System.out.print("Enter the Routing Number: ");
String s = ss.nextLine();
len = s.length();
if (len != 9) {
System.out.print("Length not 9");
} else {
String newString = s.substring(s.length() - 1);
checksum = Integer.parseInt(newString);
sum = (3 * (Integer.parseInt("" + s.charAt(0)))) + (7 * (Integer.parseInt("" + s.charAt(1))))
+ (1 * (Integer.parseInt("" + s.charAt(2)))) + (3 * (Integer.parseInt("" + s.charAt(3))))
+ (7 * (Integer.parseInt("" + s.charAt(4)))) + (1 * (Integer.parseInt("" + s.charAt(5))))
+ (3 * (Integer.parseInt("" + s.charAt(6)))) + (7 * (Integer.parseInt("" + s.charAt(7))));
mod = 10 - (sum % 10);
if (mod == checksum)
System.out.print("True");
else
System.out.print("False");
;
}
}
}

Calculator in java displays double instead if int

Hey guys i am building a java calculator and everything works fine except the fact that i am doing calculations with double numbers.
The problem is that when i want to do 0.3 + 0.5 = 0.8 works fine, but when i do 6 + 6 = 12.0
How can i fix this so when the result is .0 at the end it displays an integer?
My code is:
public void actionPerformed(ActionEvent e) {
int j = 0;
r2 = Double.parseDouble(textField.getText());
if (option.equals("+")) {
result = r1 + r2;
}
if (option.equals("-")) {
result = r1 - r2;
}
if (option.equals("*")) {
result = r1 * r2;
}
if (option.equals("/")) {
result = r1 / r2;
}
textField.setText(result + " ");
}
Use a DecimalFormat object (see the documentation at http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html).
Example:
DecimalFormat df = new DecimalFormat("############.#");
System.out.println(df.format(result));
You can check if your result is int and if it is then then set its integer value to result like this.
public void actionPerformed(ActionEvent e) {
int j = 0;
r2 = Double.parseDouble(textField.getText());
if (option.equals("+")) {
result = r1 + r2;
}
if (option.equals("-")) {
result = r1 - r2;
}
if (option.equals("*")) {
result = r1 * r2;
}
if (option.equals("/")) {
result = r1 / r2;
}
if ((result == Math.floor(result )) && !Double.isInfinite(result )) {
textField.setText((int)(result) + " ");
} else textField.setText(result + " ");
}
You can just check if result has a whole number in it, like this:
if((int) result == result) {
textField.setText((int)result + " ");
} else {
textField.setText(result + " ");
}
EDIT
As #Hovercraft Full Of Eels said, you could put more thought into deciding, what is a whole number and what is not, especialy for case when result is something like 5.99999997 and simple casting to int will make 5 from such number.
final double epsilon = 1e-6;
if(Math.abs(Math.rint(myVal) - myVal) < epsilon) {
textField.setText(Math.round(myVal) + "");
} else {
textField.setText(String.format("%f", myVal));
}

How to combine 2 images to form hybrid image?

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.

Categories

Resources