I am writing an app in threes for a set of particles, I want to include collision between the particles. It seems it only check for collisions once - three.js

It seems it only check for collisions once and particles loose speed. If anyone has an advice...
function animate() {
var elapsedTime = clock.getElapsedTime();
particlesGeometry.attributes.position.needsUpdate = true;
const paso = 1.5;
for (let i = 0; i < count; i++) {
const i3 = i * 3;var k = 0;
const x = particlesGeometry.attributes.position.array[i3 + 0];
const y = particlesGeometry.attributes.position.array[i3 + 1];
const z = particlesGeometry.attributes.position.array[i3 + 2];
for (let j=k; j < (count); j++){
const l = 3 * j;
if (l==i3){continue;}
var posx = x - particlesGeometry.attributes.position.array[l + 0];
var posy = y - particlesGeometry.attributes.position.array[l + 1];
var posz = z - particlesGeometry.attributes.position.array[l + 2];
var dist2 = Math.pow(posx,2)+Math.pow(posy,2)+Math.pow(posz,2);
var velMod1 = Math.sqrt(Math.pow(vel[l+0],2)+Math.pow(vel[l+1],2)+Math.pow(vel[l+2],2));
var velMod2 = Math.sqrt(Math.pow(vel[i3+0],2)+Math.pow(vel[i3+1],2)+Math.pow(vel[i3+2],2));
var erre = [posx, posy, posz];
var doterre = erre[0]*erre[0] + erre[1]*erre[1] + erre[2]*erre[2];
var doterreN = Math.sqrt(doterre);
var erreMod = [erre[0]/doterreN, erre[1]/doterreN, erre[2]/doterreN];
if (dist2 <=(velMod1+velMod2)*.05){
var proy1 = erreMod[0]*vel[l+0]+erreMod[1]*vel[l+1]+erreMod[2]*vel[l+2];
var proy2 = erreMod[0]*vel[i3+0]+erreMod[1]*vel[i3+1]+erreMod[2]*vel[i3+2];
vel[l + 0] = vel[l + 0] - proy1*erreMod[0];
vel[l + 1] = vel[l + 1] - proy1*erreMod[1];
vel[l + 2] = vel[l + 2] - proy1*erreMod[2];
vel[i3 + 0] = vel[i3 + 0] - proy2*erreMod[0];
vel[i3 + 1] = vel[i3 + 1] - proy2*erreMod[1];
vel[i3 + 2] = vel[i3 + 2] - proy2*erreMod[2];
particlesGeometry.attributes.color.array[i3+0] = 1;
particlesGeometry.attributes.color.array[i3+1] = 1;
particlesGeometry.attributes.color.array[i3+2] = 1;
particlesGeometry.attributes.color.array[l+0] = 1;
particlesGeometry.attributes.color.array[l+1] = 1;
particlesGeometry.attributes.color.array[l+2] = 1;
}
}
k++;
if (x>=0 || x<=-5){vel[i3+0]=-vel[i3+0]}
if (y>=5 || y<=-5){vel[i3+1]=-vel[i3+1]}
if (z>=5 || z<=-5){vel[i3+2]=-vel[i3+2]}
particlesGeometry.attributes.position.array[i3 + 0] = x + vel[i3+0]*paso;
particlesGeometry.attributes.position.array[i3 + 1] = y + vel[i3+1]*paso;
particlesGeometry.attributes.position.array[i3 + 2] = z + vel[i3+2]*paso;
}
Paso is the step. What I did was to invert the velocity component of the colliding particles along the vector that joins the particles. First I've tried with the dot function for dot product from mathjs but it was too slow so I've coded the dot products, mainly for normalization. The idea is the collision condition is checked for every pair of particles once.
dist2 <=(velMod1+velMod2)*.05
That means the square of the distance between particles must be less than or equal to the sum of their velocities times the step. That latter is in order to avoid particles to oscillate in the collision zone.
In order to check for collision events I've painted the particles that collided on white. The number of white particles should rise as time elapses but that is not the case when running the program.
particlesGeometry.attributes.color.array[i3+0] = 1;
particlesGeometry.attributes.color.array[i3+1] = 1;
particlesGeometry.attributes.color.array[i3+2] = 1;
particlesGeometry.attributes.color.array[l+0] = 1;
particlesGeometry.attributes.color.array[l+1] = 1;
particlesGeometry.attributes.color.array[l+2] = 1;
Thank you.
I've tried to write the double iteration in different forms, the same for the vector operations but the results were funny.

Related

How to speed up Get func in p5.js?

Is there any way to speed up this piece of code (simplified)? On my Dell m4700 laptop, it works for 1 minute and 10 seconds (the size of the canvas is 1000x1400 pixels).
pg = createGraphics(1000,1400);
pg.pixelDensity(1);
***
for(j=0;j<pg.height;j++){
for(i=0;i<pg.width;i++){
pg.stroke(cc=pg.get(i,j));
pg.point(i,j+4);
}
}
Without this line,
pg.stroke(cc=pg.get(i,j));
the code executes in milliseconds.
I made another version that works in 20 seconds, but for some reason the result is slightly different visually:
for(j=0;j<pg.height;j++){
pg.loadPixels();
for(i=0;i<pg.width;i++){
let pi = i + (j * pg.width);
let ri = pi * 4;
let cr = pg.pixels[ri];
let cg = pg.pixels[ri + 1];
let cb = pg.pixels[ri + 2];
let ca = pg.pixels[ri + 3];
pg.stroke(color(cr,cg,cb,ca));
pg.point(i,floor(j+4));
}
}
Big edit:
Ok, I miss read the question and was thinking in java's processing not p5js as the OP has properly indicated. So my answer was very wrong. Sorry.
But still the approach exists in p5js and is faster.
p5js store pixels in 1d array, 4 slots for each pixel:
[pix1R, pix1G, pix1B, pix1A, pix2R, pix2G, pix2B, pix2A...]
And also the pixel density mathers.
So the code is different, I belive you are looking for something like (no pg here, but the thinking is the same):
loadPixels();
let d = pixelDensity();
let imagesize = 4 * (width * d) * ((height) * d);
for (let i = 0; i <= imagesize; i += 4) {
let j = i + 16;//4*4
pixels[i] = pixels[j];
pixels[i + 1] = pixels[j + 1];
pixels[i + 2] = pixels[j + 2];
pixels[i + 3] = pixels[j + 3];
}
updatePixels();
Now, to access a given area in the array is a little convoluted, here an example
//the area data
const area_x = 35;
const area_y = 48;
const width_of_area = 180;
const height_of_area = 200;
//the pixel density
const d = pixelDensity();
loadPixels();
// those 2 first loops goes trough every pixel in the area
for (let x = area_x; x < width_of_area; x++) {
for (let y = area_y; y < height_of_area; y++) {
//here we go trough the pixels array to get each value of a pixel
for (let i = 0; i < d; i++) {
for (let j = 0; j < d; j++) {
// calculate the index of the 1d array for every pixel
// 4 values in the array for each pixel
// y times density times #of pixels plus
// x times density times #of pixels
index = 4 * ((y * d + j) * width * d + (x * d + i));
// You can assign raw values for rgb color
pixels[index] = 255;
pixels[index + 1] = 30;
pixels[index + 2] = 200;
pixels[index + 3] = 255;
}
}
}
}
updatePixels();
Both this examples are at p5js online editor:
1:https://editor.p5js.org/v-k-/sketches/GGVeZvCk7
2: https://editor.p5js.org/v-k-/sketches/kW9lXyK2n
Hope that helps, and sorry for the previus processing answer/code.
cheers

How to simplify shapes for triangulation with three.js and jsclipper

I try to display geometry which is constructed by constructpath commands like moveto lineto beziercurveto in Three.js.
Therefore I create a THREE.ShapePath(); and execute the command toShapes(isClockwise).
After this I use THREE.ExtrudeBufferGeometry to create the 3D shape.
Unfortunately the shapes are sometimes really complex and are not created correctly which means they are distorted.
Using libtess as triangulation library solves some issues. But I have still distorted geometry.
Now I want to use jsclipper to simplify the shapes prior triangulation.
I modified three.js in such way:
in the method addShape in ExtrudeBufferGeometry I have added:
$.each(vertices, function(index, item) {
vertices[index]['X'] = vertices[index]['x'];
vertices[index]['Y'] = vertices[index]['y'];
delete vertices[index]['x'];
delete vertices[index]['y'];
});
if (holes[0]) {
for (i = 0; i < holes.length; i++ ) {
$.each(holes[i], function(index, item) {
holes[i][index]['X'] = holes[i][index]['x'];
holes[i][index]['Y'] = holes[i][index]['y'];
delete holes[i][index]['x'];
delete holes[i][index]['y'];
});
}
}
var scale = 100;
ClipperLib.JS.ScaleUpPaths([vertices], scale);
if (holes[0]) {
ClipperLib.JS.ScaleUpPaths(holes, scale);
}
vertices = ClipperLib.Clipper.SimplifyPolygons([vertices], ClipperLib.PolyFillType.pftNonZero);
// or ClipperLib.PolyFillType.pftEvenOdd
if (holes[0]) {
holes = ClipperLib.Clipper.SimplifyPolygons(holes, ClipperLib.PolyFillType.pftNonZero);
// or ClipperLib.PolyFillType.pftEvenOdd
}
// var cleandelta = 0.1; // 0.1 should be the appropriate delta in different cases
// vertices = ClipperLib.Clipper.CleanPolygons([vertices], cleandelta * scale);
// if (holes[0]) {
// holes = ClipperLib.Clipper.CleanPolygons(holes, cleandelta * scale);
// }
ClipperLib.JS.ScaleDownPaths(vertices, scale);
if (holes[0]) {
ClipperLib.JS.ScaleDownPaths(holes, scale);
}
for (i = 0; i < vertices.length; i++ ) {
$.each(vertices[i], function(index, item) {
vertices[i][index]['x'] = vertices[i][index]['X'];
vertices[i][index]['y'] = vertices[i][index]['Y'];
delete vertices[i][index]['X'];
delete vertices[i][index]['Y'];
});
}
if (holes[0]) {
for (i = 0; i < holes.length; i++ ) {
$.each(holes[i], function(index, item) {
holes[i][index]['x'] = holes[i][index]['X'];
holes[i][index]['y'] = holes[i][index]['Y'];
delete holes[i][index]['X'];
delete holes[i][index]['Y'];
});
}
}
Now I can see that the vertices are "reduced".
But var faces = ShapeUtils.triangulateShape( vertices, holes ); doesn't generate faces for some examples anymore.
Please can one help how to simplify the shapes correctly?
A bit hard to figure out what the problem is actually. Clipper (also when using SimplifyPolygons or SimplifyPolygon) can only produce weakly-simple polygons, which means that there can be pseudo-duplicate points: although sequential coordinates are quaranteed to be not indentical, some of the next points can share the same coordinate. Also a coordinate can be on the line between two points.
After simplifying (or any other boolean operation) you could make a cleaning step using Offsetting with a small negative value: https://sourceforge.net/p/jsclipper/wiki/documentation/#clipperlibclipperoffsetexecute.
This possibly removes all of the pseudo-duplicate points.
I have made also a float version of Clipper (http://jsclipper.sourceforge.net/6.4.2.2_fpoint/). It is extensively tested, but because Angus Johnson, the author of the original C# Clipper (of which JS-version is ported from), has thought that using floats causes robustness problems although according to my tests the are no such, the original C# float version does not exists. The float version is simpler to use and you can try there a small negative offset: eg. -0.001 or -0.01.
You could also give a try to PolyTree or ExPolygons (https://sourceforge.net/p/jsclipper/wiki/ExPolygons%20and%20PolyTree%206/). ExPolygons can be used to get holes and contours and PolyTree can be used to get the full parent-child-relationship of holes and contours.
The last resort is a broken-pen-nib -function. It detects all pseudo-duplicate points and make a broken-pen-nib -effect to them, so that the result is free of any duplicates. The attached images shows what this effect means using large nib-effect-value to make the effect meaning clearer. Three.js polygon triangulation fails in pseudo duplicate points. There are a discussion https://github.com/mrdoob/three.js/issues/3386 of this subject.
// Make polygons to simple by making "a broken pen tip" effect on each semi-adjacent (duplicate) vertex
// ORIGPOLY can be a contour
// or exPolygon structure
function BreakPenNibs(ORIGPOLY, dist, scale)
{
if (!dist || dist < 0) return;
var sqrt = Math.sqrt;
var allpoints = {}, point = {};
var key = "";
var currX = 0.0,
currY = 0.0;
var prevX = 0.0,
prevY = 0.0;
var nextX = 0.0,
nextY;
var x = 0.0,
y = 0.0,
length = 0.0,
i = 0,
duplcount = 0,
j = 0;
var prev_i = 0,
next_i = 0,
last_i;
var extra_vertices = new Array(100),
moved_vertices = new Array(100);
// Get first all duplicates
var duplicates = new Array(100),
indexi = "",
indexstr = "",
arraystr = "",
polys, outer, holes;
if (ORIGPOLY instanceof Array)
{
outer = ORIGPOLY;
}
else if (ORIGPOLY.outer instanceof Array)
{
outer = ORIGPOLY.outer;
}
else return;
if (ORIGPOLY.holes instanceof Array) holes = ORIGPOLY.holes;
else holes = [];
polys = [outer].concat(holes);
var polys_length = polys.length;
// Get first max lenght of arrays
var max_index_len = 0;
var arr_len;
i = polys_length;
while (i--)
{
arr_len = polys[i].length;
if (arr_len > max_index_len) max_index_len = arr_len;
}
max_index_len = max_index_len.toString().length;
var max_polys_length = polys_length.toString().length;
var poly;
j = polys_length;
var scaling = scale/10;
while (j--)
{
poly = polys[j];
ilen = poly.length;
i = ilen;
while (i--)
{
point = poly[i];
//key = Math.round(point.X) + ":" + Math.round(point.Y);
key = (Math.round(point.X / scaling) * scaling)
+ ":" + (Math.round(point.Y / scaling) * scaling);
indexi = allpoints[key];
if (typeof (indexi) != "undefined")
{
// first found duplicate
duplicates[duplcount] = indexi;
duplcount++;
arraystr = j.toString();
while (arraystr.length < max_polys_length) arraystr = "0" + arraystr;
indexstr = i.toString();
while (indexstr.length < max_index_len) indexstr = "0" + indexstr;
duplicates[duplcount] = arraystr + "." + indexstr;
duplcount++;
}
arraystr = j.toString();
while (arraystr.length < max_polys_length) arraystr = "0" + arraystr;
indexstr = i.toString();
while (indexstr.length < max_index_len) indexstr = "0" + indexstr;
allpoints[key] = arraystr + "." + indexstr;
}
}
if (!duplcount) return;
duplicates.length = duplcount;
duplicates.sort();
//console.log(JSON.stringify(duplicates));
var splitted, poly_index = 0,
nth_dupl = 0;
var prev_poly_index = -1;
poly_index = 0;
for (j = 0; j < duplcount; j++)
{
splitted = duplicates[j].split(".");
poly_index = parseInt(splitted[0], 10);
if (poly_index != prev_poly_index) nth_dupl = 0;
else nth_dupl++;
i = parseInt(splitted[1], 10);
poly = polys[poly_index];
len = poly.length;
if (poly[0].X === poly[len - 1].X &&
poly[0].Y === poly[len - 1].Y)
{
last_i = len - 2;
}
else
{
last_i = len - 1;
}
point = poly[i];
// Calculate "broken pen tip" effect
// for current point by finding
// a coordinate at a distance dist
// along the edge between current and
// previous point
// This is inlined to maximize speed
currX = point.X;
currY = point.Y;
if (i === 0) prev_i = last_i; // last element in array
else prev_i = i - 1;
prevX = poly[prev_i].X;
prevY = poly[prev_i].Y;
x=0;y=0;
if (!point.Collinear)
{
length = sqrt((-currX + prevX) * (-currX + prevX) + (currY - prevY) * (currY - prevY));
//console.log(length);
x = currX - (dist * (currX - prevX)) / length;
y = currY - (dist * (currY - prevY)) / length;
}
// save the found (calculated) point
moved_vertices[j] = {
X: x,
Y: y,
Collinear:point.Collinear,
index: i,
poly_index: poly_index
};
// "broken nib effect" for next point also
if (i == len - 1) next_i = 0;
else next_i = i + 1;
nextX = poly[next_i].X;
nextY = poly[next_i].Y;
x=0;y=0;
if (!point.Collinear)
{
length = sqrt((-currX + nextX) * (-currX + nextX) + (currY - nextY) * (currY - nextY));
x = currX - (dist * (currX - nextX)) / length;
y = currY - (dist * (currY - nextY)) / length;
}
// save the found (calculated) point
extra_vertices[j] = {
X: x,
Y: y,
Collinear:point.Collinear,
index: i + nth_dupl,
poly_index: poly_index
};
prev_poly_index = poly_index;
}
moved_vertices.length = extra_vertices.length = duplcount;
//console.log("MOVED:" + JSON.stringify(moved_vertices));
//console.log("EXTRA:" + JSON.stringify(extra_vertices));
// Update moved coordinates
i = duplcount;
var point2;
while (i--)
{
point = moved_vertices[i];
x = point.X;
y = point.Y;
// Faster than isNaN: http://jsperf.com/isnan-alternatives
if (x != x || x == Infinity || x == -Infinity) continue;
if (y != y || y == Infinity || y == -Infinity) continue;
point2 = polys[point.poly_index][point.index];
point2.X = point.X;
point2.Y = point.Y;
point2.Collinear = point.Collinear;
}
// Add an extra vertex
// This is needed to remain the angle of the next edge
for (i = 0; i < duplcount; i++)
{
point = extra_vertices[i];
x = point.X;
y = point.Y;
// Faster than isNaN: http://jsperf.com/isnan-alternatives
if (x != x || x == Infinity || x == -Infinity) continue;
if (y != y || y == Infinity || y == -Infinity) continue;
polys[point.poly_index].splice(point.index + 1, 0,
{
X: point.X,
Y: point.Y,
Collinear: point.Collinear
});
}
// Remove collinear points
// and for some reason coming
// sequential duplicates
// TODO: check why seq. duplicates becomes
j = polys.length;
var prev_point = null;
while (j--)
{
poly = polys[j];
ilen = poly.length;
i = ilen;
while (i--)
{
point = poly[i];
if(prev_point!=null && point.X == prev_point.X && point.Y == prev_point.Y) poly.splice(i, 1);
else
if(point.Collinear) poly.splice(i, 1);
prev_point = point;
}
}
//console.log(JSON.stringify(polys));
// because original array is modified, no need to return anything
}
var BreakPenNipsOfExPolygons = function (exPolygons, dist, scale)
{
var i = 0,
j = 0,
ilen = exPolygons.length,
jlen = 0;
for (; i < ilen; i++)
{
//if(i!=4) continue;
BreakPenNibs(exPolygons[i], dist, scale);
}
};

resetting the particular sudoku box in p5?

I am trying to implement a Sudoku table in p5.js, I am able to implement a cell where I can write a number (1-9) down. But I cannot remove a number, i.e. if I write '1' first on a cell and write '2', it writes on top of it.
So, how can I remove the existing number and write a different one?
EDIT:
my code till now:
//make a grid
function makegrid(rows, cols) {
var regrid = new Array(rows);
for (var i = 0; i < rows; i++) {
regrid[i] = new Array(cols);
}
return regrid;
}
var numrec = [];
var rows = 9;
var grid = [];
var cols = 9;
var w = 50;
var input;
//show the boxes
function show(i, j) {
this.i = i;
this.j = j;
var x = w * this.i;
var y = w * this.j;
noFill();
//input = createInput();
//input.position(x+5,y+5,w);
strokeWeight(1);
rect(x + 5, y + 5, w, w); //just to see line clearly
}
//there must be a better way to do it but for now ---> here we go for separation
// of tables
function boldlines() {
strokeWeight(4);
stroke(51);
line(5, 5, 5, w * 9 + 5);
line(w * 3 + 5, 5, w * 3 + 5, w * 9 + 5);
line(w * 6 + 5, 5, w * 6 + 5, w * 9 + 5);
line(5, w * 9 + 5, w * 9 + 5, w * 9 + 5);
line(5, 5, w * 9 + 5, 5);
line(w * 9 + 5, 5, w * 9 + 5, w * 9 + 5);
line(5, w * 3 + 5, w * 9 + 5, w * 3 + 5);
line(5, w * 6 + 5, w * 9 + 5, w * 6 + 5);
}
function setup() {
createCanvas(600, 600);
grid = makegrid(rows, cols);
numrec = makegrid(rows, cols);
for (var i = 0; i < rows; i++) {
for (var j = 0; j < cols; j++) {
numrec[i][j] = 1;
}
}
}
function draw() {
boldlines();
for (var i = 0; i < rows; i++) {
for (var j = 0; j < cols; j++) {
show(i, j);
//console.log(mouseX,mouseY);
}
}
}
function numput(x, y, num) {
//background(0);
if (num === 0) {
num = "";
}
textSize(30);
//textAlign(CENTER);
text(num, x + 30, y + 40);
}
function mousePressed() {
var mx = mouseX;
var my = mouseY;
var i = floor((mx + 5) / w);
var j = floor((my + 5) / w);
if (i >= 0 && j >= 0 && i < rows && j < cols) {
//console.log(i, j);
var num = numrec[i][j];
if (num === 10) {
num = 0;
}
numrec[i][j] = num + 1;
numput(i * w, j * w, num);
}
}
I figured out a way to hide old number in that cell and retain the content of all the other cells. I hid the previous number by drawing a rectangle on top of it with the same dimensions of that of a cell and then updating the cell with new number.
function numput(x, y, num) {
//background(0);
if (num === 0) {
num = "";
}
textSize(30);
//textAlign(CENTER);
//Newly added
strokeWeight(0);
fill(255,255,255);
rect(x+4 , y+4 , w, w);
boldlines();
text(num, x + 30, y + 40);
}
I have done some changes in function numput() to achieve it.

Obtaining orientation map of fingerprint image using OpenCV

I'm trying to implement the method of improving fingerprint images by Anil Jain. As a starter, I encountered some difficulties while extracting the orientation image, and am strictly following those steps described in Section 2.4 of that paper.
So, this is the input image:
And this is after normalization using exactly the same method as in that paper:
I'm expecting to see something like this (an example from the internet):
However, this is what I got for displaying obtained orientation matrix:
Obviously this is wrong, and it also gives non-zero values for those zero points in the original input image.
This is the code I wrote:
cv::Mat orientation(cv::Mat inputImage)
{
cv::Mat orientationMat = cv::Mat::zeros(inputImage.size(), CV_8UC1);
// compute gradients at each pixel
cv::Mat grad_x, grad_y;
cv::Sobel(inputImage, grad_x, CV_16SC1, 1, 0, 3, 1, 0, cv::BORDER_DEFAULT);
cv::Sobel(inputImage, grad_y, CV_16SC1, 0, 1, 3, 1, 0, cv::BORDER_DEFAULT);
cv::Mat Vx, Vy, theta, lowPassX, lowPassY;
cv::Mat lowPassX2, lowPassY2;
Vx = cv::Mat::zeros(inputImage.size(), inputImage.type());
Vx.copyTo(Vy);
Vx.copyTo(theta);
Vx.copyTo(lowPassX);
Vx.copyTo(lowPassY);
Vx.copyTo(lowPassX2);
Vx.copyTo(lowPassY2);
// estimate the local orientation of each block
int blockSize = 16;
for(int i = blockSize/2; i < inputImage.rows - blockSize/2; i+=blockSize)
{
for(int j = blockSize / 2; j < inputImage.cols - blockSize/2; j+= blockSize)
{
float sum1 = 0.0;
float sum2 = 0.0;
for ( int u = i - blockSize/2; u < i + blockSize/2; u++)
{
for( int v = j - blockSize/2; v < j+blockSize/2; v++)
{
sum1 += grad_x.at<float>(u,v) * grad_y.at<float>(u,v);
sum2 += (grad_x.at<float>(u,v)*grad_x.at<float>(u,v)) * (grad_y.at<float>(u,v)*grad_y.at<float>(u,v));
}
}
Vx.at<float>(i,j) = sum1;
Vy.at<float>(i,j) = sum2;
double calc = 0.0;
if(sum1 != 0 && sum2 != 0)
{
calc = 0.5 * atan(Vy.at<float>(i,j) / Vx.at<float>(i,j));
}
theta.at<float>(i,j) = calc;
// Perform low-pass filtering
float angle = 2 * calc;
lowPassX.at<float>(i,j) = cos(angle * pi / 180);
lowPassY.at<float>(i,j) = sin(angle * pi / 180);
float sum3 = 0.0;
float sum4 = 0.0;
for(int u = -lowPassSize / 2; u < lowPassSize / 2; u++)
{
for(int v = -lowPassSize / 2; v < lowPassSize / 2; v++)
{
sum3 += inputImage.at<float>(u,v) * lowPassX.at<float>(i - u*lowPassSize, j - v * lowPassSize);
sum4 += inputImage.at<float>(u, v) * lowPassY.at<float>(i - u*lowPassSize, j - v * lowPassSize);
}
}
lowPassX2.at<float>(i,j) = sum3;
lowPassY2.at<float>(i,j) = sum4;
float calc2 = 0.0;
if(sum3 != 0 && sum4 != 0)
{
calc2 = 0.5 * atan(lowPassY2.at<float>(i, j) / lowPassX2.at<float>(i, j)) * 180 / pi;
}
orientationMat.at<float>(i,j) = calc2;
}
}
return orientationMat;
}
I've already searched a lot on the web, but almost all of them are in Matlab. And there exist very few ones using OpenCV, but they didn't help me either. I sincerely hope someone could go through my code and point out any error to help. Thank you in advance.
Update
Here are the steps that I followed according to the paper:
Obtain normalized image G.
Divide G into blocks of size wxw (16x16).
Compute the x and y gradients at each pixel (i,j).
Estimate the local orientation of each block centered at pixel (i,j) using equations:
Perform low-pass filtering to remove noise. For that, convert the orientation image into a continuous vector field defined as:
where W is a two-dimensional low-pass filter, and w(phi) x w(phi) is its size, which equals to 5.
Finally, compute the local ridge orientation at (i,j) using:
Update2
This is the output of orientationMat after changing the mat type to CV_16SC1 in Sobel operation as Micka suggested:
Maybe it's too late for me to answer, but anyway somebody could read this later and solve the same problem.
I've been working for a while in the same algorithm, same method you posted... But there's some writting errors when the papper was redacted (I guess). After fighting a lot with the equations I found this errors by looking other similar works.
Here is what worked for me...
Vy(i, j) = 2*dx(u,v)*dy(u,v)
Vx(i,j) = dx(u,v)^2 - dy(u,v)^2
O(i,j) = 0.5*arctan(Vy(i,j)/Vx(i,j)
(Excuse me I wasn't able to post images, so I wrote the modified ecuations. Remeber "u" and "v" are positions of the summation across the BlockSize by BlockSize window)
The first thing and most important (obviously) are the equations, I saw that in different works this expressions were really different and in every one they talked about the same algorithm of Hong et al.
The Key is finding the Least Mean Square (First 3 equations) of the gradients (Vx and Vy), I provided the corrected formulas above for this ation. Then you can compute angle theta for the non overlapping window (16x16 size recommended in the papper), after that the algorithm says you must calculate the magnitud of the doubled angle in "x" and "y" directions (Phi_x and Phi_y).
Phi_x(i,j) = V(i,j) * cos(2*O(i,j))
Phi_y(i,j) = V(i,j) * sin(2*O(i,j))
Magnitud is just:
V = sqrt(Vx(i,j)^2 + Vy(i,j)^2)
Note that in the related work doesn't mention that you have to use the gradient magnitud, but it make sense (for me) in doing it. After all this corrections you can apply the low pass filter to Phi_x and Phi_y, I used a simple Mask of size 5x5 to average this magnitudes (something like medianblur() of opencv).
Last thing is to calculate new angle, that is the average of the 25ith neighbors in the O(i,j) image, for this you just have to:
O'(i,j) = 0.5*arctan(Phi_y/Phi_x)
We're just there... All this just for calculating the angle of the NORMAL VECTOR TO THE RIDGES DIRECTIONS (O'(i,j)) in the BlockSize by BlockSize non overlapping window, what does it mean? it means that the angle we just calculated is perpendicular to the ridges, in simple words we just calculated the angle of the riges plus 90 degrees... To get the angle we need, we just have to substract to the obtained angle 90°.
To draw the lines we need to have an initial point (X0, Y0) and a final point(X1, Y1). For that imagine a circle centered on (X0, Y0) with a radious of "r":
x0 = i + blocksize/2
y0 = j + blocksize/2
r = blocksize/2
Note we add i and j to the first coordinates becouse the window is moving and we are gonna draw the line starting from the center of the non overlaping window, so we can't use just the center of the non overlaping window.
Then to calculate the end coordinates to draw a line we can just have to use a right triangle so...
X1 = r*cos(O'(i,j)-90°)+X0
Y1 = r*sin(O'(i,j)-90°)+Y0
X2 = X0-r*cos(O'(i,j)-90°)
Y2 = Y0-r*cos(O'(i,j)-90°)
Then just use opencv line function, where initial Point is (X0,Y0) and final Point is (X1, Y1). Additional to it, I drawed the windows of 16x16 and computed the oposite points of X1 and Y1 (X2 and Y2) to draw a line of the entire window.
Hope this help somebody.
My results...
Main function:
Mat mat = imread("nwmPa.png",0);
mat.convertTo(mat, CV_32F, 1.0/255, 0);
Normalize(mat);
int blockSize = 6;
int height = mat.rows;
int width = mat.cols;
Mat orientationMap;
orientation(mat, orientationMap, blockSize);
Normalize:
void Normalize(Mat & image)
{
Scalar mean, dev;
meanStdDev(image, mean, dev);
double M = mean.val[0];
double D = dev.val[0];
for(int i(0) ; i<image.rows ; i++)
{
for(int j(0) ; j<image.cols ; j++)
{
if(image.at<float>(i,j) > M)
image.at<float>(i,j) = 100.0/255 + sqrt( 100.0/255*pow(image.at<float>(i,j)-M,2)/D );
else
image.at<float>(i,j) = 100.0/255 - sqrt( 100.0/255*pow(image.at<float>(i,j)-M,2)/D );
}
}
}
Orientation map:
void orientation(const Mat &inputImage, Mat &orientationMap, int blockSize)
{
Mat fprintWithDirectionsSmoo = inputImage.clone();
Mat tmp(inputImage.size(), inputImage.type());
Mat coherence(inputImage.size(), inputImage.type());
orientationMap = tmp.clone();
//Gradiants x and y
Mat grad_x, grad_y;
// Sobel(inputImage, grad_x, CV_32F, 1, 0, 3, 1, 0, BORDER_DEFAULT);
// Sobel(inputImage, grad_y, CV_32F, 0, 1, 3, 1, 0, BORDER_DEFAULT);
Scharr(inputImage, grad_x, CV_32F, 1, 0, 1, 0);
Scharr(inputImage, grad_y, CV_32F, 0, 1, 1, 0);
//Vector vield
Mat Fx(inputImage.size(), inputImage.type()),
Fy(inputImage.size(), inputImage.type()),
Fx_gauss,
Fy_gauss;
Mat smoothed(inputImage.size(), inputImage.type());
// Local orientation for each block
int width = inputImage.cols;
int height = inputImage.rows;
int blockH;
int blockW;
//select block
for(int i = 0; i < height; i+=blockSize)
{
for(int j = 0; j < width; j+=blockSize)
{
float Gsx = 0.0;
float Gsy = 0.0;
float Gxx = 0.0;
float Gyy = 0.0;
//for check bounds of img
blockH = ((height-i)<blockSize)?(height-i):blockSize;
blockW = ((width-j)<blockSize)?(width-j):blockSize;
//average at block WхW
for ( int u = i ; u < i + blockH; u++)
{
for( int v = j ; v < j + blockW ; v++)
{
Gsx += (grad_x.at<float>(u,v)*grad_x.at<float>(u,v)) - (grad_y.at<float>(u,v)*grad_y.at<float>(u,v));
Gsy += 2*grad_x.at<float>(u,v) * grad_y.at<float>(u,v);
Gxx += grad_x.at<float>(u,v)*grad_x.at<float>(u,v);
Gyy += grad_y.at<float>(u,v)*grad_y.at<float>(u,v);
}
}
float coh = sqrt(pow(Gsx,2) + pow(Gsy,2)) / (Gxx + Gyy);
//smoothed
float fi = 0.5*fastAtan2(Gsy, Gsx)*CV_PI/180;
Fx.at<float>(i,j) = cos(2*fi);
Fy.at<float>(i,j) = sin(2*fi);
//fill blocks
for ( int u = i ; u < i + blockH; u++)
{
for( int v = j ; v < j + blockW ; v++)
{
orientationMap.at<float>(u,v) = fi;
Fx.at<float>(u,v) = Fx.at<float>(i,j);
Fy.at<float>(u,v) = Fy.at<float>(i,j);
coherence.at<float>(u,v) = (coh<0.85)?1:0;
}
}
}
} ///for
GaussConvolveWithStep(Fx, Fx_gauss, 5, blockSize);
GaussConvolveWithStep(Fy, Fy_gauss, 5, blockSize);
for(int m = 0; m < height; m++)
{
for(int n = 0; n < width; n++)
{
smoothed.at<float>(m,n) = 0.5*fastAtan2(Fy_gauss.at<float>(m,n), Fx_gauss.at<float>(m,n))*CV_PI/180;
if((m%blockSize)==0 && (n%blockSize)==0){
int x = n;
int y = m;
int ln = sqrt(2*pow(blockSize,2))/2;
float dx = ln*cos( smoothed.at<float>(m,n) - CV_PI/2);
float dy = ln*sin( smoothed.at<float>(m,n) - CV_PI/2);
arrowedLine(fprintWithDirectionsSmoo, Point(x, y+blockH), Point(x + dx, y + blockW + dy), Scalar::all(255), 1, CV_AA, 0, 0.06*blockSize);
// qDebug () << Fx_gauss.at<float>(m,n) << Fy_gauss.at<float>(m,n) << smoothed.at<float>(m,n);
// imshow("Orientation", fprintWithDirectionsSmoo);
// waitKey(0);
}
}
}///for2
normalize(orientationMap, orientationMap,0,1,NORM_MINMAX);
imshow("Orientation field", orientationMap);
orientationMap = smoothed.clone();
normalize(smoothed, smoothed, 0, 1, NORM_MINMAX);
imshow("Smoothed orientation field", smoothed);
imshow("Coherence", coherence);
imshow("Orientation", fprintWithDirectionsSmoo);
}
seems nothing forgot )
I have read your code thoroughly and found that you have made a mistake while calculating sum3 and sum4:
sum3 += inputImage.at<float>(u,v) * lowPassX.at<float>(i - u*lowPassSize, j - v * lowPassSize);
sum4 += inputImage.at<float>(u, v) * lowPassY.at<float>(i - u*lowPassSize, j - v * lowPassSize);
instead of inputImage you should use a low pass filter.

Severely Laggy Bounding Box Detection

I have a bounding box collision detection system for a basic game. Each time I spawn in an entity a bounding box is paired with it. The collision system it self works; however it is extremely laggy even for just two entities. My code is listed below, I know it is definitively not the most efficient way to do this, but I don't really know how to do it any other way.
bbX, bbY,and bbZ are the position of the AABB's in the world.
float radX1,radX2;
float radY1,radY2;
float radZ1,radZ2;
float arr[12];
radX1 = (bb->maxX - bb->minX) / 2;
radX2 = (this->maxX - this->minX) / 2;
radY1 = (bb->maxY - bb->minY) / 2;
radY2 = (this->maxY - this->minY) / 2;
radZ1 = (bb->maxZ - bb->minZ) / 2;
radZ2 = (this->maxZ - this->minZ) / 2;
arr[1] = bb->bbX - 0.5f - radX1;
arr[2] = bb->bbX - 0.5f + radX1;
arr[3] = bb->bbY - 0.5f - radY1;
arr[4] = bb->bbY - 0.5f + radY1;
arr[5] = bb->bbZ - 0.5f - radZ1;
arr[6] = bb->bbZ - 0.5f + radZ1;
//this coords
arr[7] = this->bbX - 0.5f - radX2;
arr[8] = this->bbX - 0.5f + radX2;
arr[9] = this->bbY - 0.5f - radY2;
arr[10] = this->bbY - 0.5f + radY2;
arr[11] = this->bbZ - 0.5f - radZ2;
arr[12] = this->bbZ - 0.5f + radZ2;
if(arr[2] >= arr[7] && arr[1] <= arr[8])
{
if(arr[4] >= arr[9] && arr[3] <= arr[10])
{
if(arr[6] >= arr[11] && arr[5] <= arr[12])
{
this->collided = TRUE;
OutputDebugStringA("Collided!\n");
return TRUE;
}
}
}
This function is called on a timer approximately every 15ms, but increasing the iterations didn't help much either.
The function that does the work of comparing existing bounding boxes:
aabbPool is a list that stores all the AABB's currently loaded.
for(auto i = this->aabbPool.begin();i < this->aabbPool.end();++i)
{
OutputDebugStringA("Called!\n");
if(*i == NULL) ;
else
{
exe = *i;
for(auto k = this->aabbPool.begin();k < this->aabbPool.end();++k)
{
comp = *k;
if(exe->id == comp->id) ;
else
{
if(exe->isCollidedWith(comp)) OutputDebugStringA("Collided!\n");
}
}
}
}

Resources