_reg_blockMatching.cpp 60.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 *  _reg_blockMatching.cpp
 *  
 *
 *  Created by Marc Modat and Pankaj Daga on 24/03/2009.
 *  Copyright (c) 2009, University College London. All rights reserved.
 *  Centre for Medical Image Computing (CMIC)
 *  See the LICENSE.txt file in the nifty_reg root folder
 *
 */

#include "_reg_blockMatching.h"
#include "_reg_affineTransformation.h"
#include <queue>
#include <iostream>

17
/* *************************************************************** */
18 19 20
// Helper function: Get the square of the Euclidean distance
double get_square_distance(float * first_point3D, float * second_point3D)
{
21 22 23 24 25 26 27 28
    return  sqrt((first_point3D[0]-second_point3D[0])*(first_point3D[0]-second_point3D[0]) +
        (first_point3D[1]-second_point3D[1])*(first_point3D[1]-second_point3D[1]) +
        (first_point3D[2]-second_point3D[2])*(first_point3D[2]-second_point3D[2]));
}
double get_square_distance2D(float * first_point2D, float * second_point2D)
{
    return  sqrt((first_point2D[0]-second_point2D[0])*(first_point2D[0]-second_point2D[0]) +
        (first_point2D[1]-second_point2D[1])*(first_point2D[1]-second_point2D[1]));
29 30
}

31
/* *************************************************************** */
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
// Heap sort
void reg_heapSort(float *array_tmp, int *index_tmp, int blockNum)
{
	float *array = &array_tmp[-1];
	int *index = &index_tmp[-1];
	int l=(blockNum >> 1)+1;
	int ir=blockNum;
	float val;
	int iVal;
	for(;;){
		if(l>1){
			val=array[--l];
			iVal=index[l];
		}
		else{
			val=array[ir];
			iVal=index[ir];
			array[ir]=array[1];
			index[ir]=index[1];
			if(--ir == 1){
				array[1]=val;
				index[1]=iVal;
				break;
			}
		}
		int i=l;
		int j=l+l;
		while(j<=ir){
			if(j<ir && array[j]<array[j+1]) j++;
			if(val<array[j]){
				array[i]=array[j];
				index[i]=index[j];
				i=j;
				j<<=1;
			}
			else break;
		}
		array[i]=val;
		index[i]=iVal;
	}
}
73 74
/* *************************************************************** */
/* *************************************************************** */
75
template <class DTYPE>
76
void _reg_set_active_blocks(nifti_image *targetImage, _reg_blockMatchingParam *params, int *mask, bool runningOnGPU)
77 78 79
{
	const int totalBlockNumber = params->blockNumber[0]*params->blockNumber[1]*params->blockNumber[2];
	float *varianceArray=(float *)malloc(totalBlockNumber*sizeof(float));
80 81 82
    int *indexArray=(int *)malloc(totalBlockNumber*sizeof(int));

    int *maskPtr=&mask[0];
83 84

	int unusableBlock=0;
85
    int index;
86

87
    DTYPE *targetValues = (DTYPE *)malloc(BLOCK_SIZE * sizeof(DTYPE));
88
	DTYPE *targetPtr = static_cast<DTYPE *>(targetImage->data);
89
	int blockIndex=0;
90 91 92 93 94 95

    if(targetImage->nz>1){
        // Version using 3D blocks
	    for(int k=0; k<params->blockNumber[2]; k++){
		    for(int j=0; j<params->blockNumber[1]; j++){
			    for(int i=0; i<params->blockNumber[0]; i++){
96

97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
                    memset(targetValues, 0, BLOCK_SIZE * sizeof(DTYPE));
				    float mean=0.0f;
				    float voxelNumber=0.0f;
                    int coord=0;
				    for(int z=k*BLOCK_WIDTH; z<(k+1)*BLOCK_WIDTH; z++){
					    if(z<targetImage->nz){
                            index =z*targetImage->nx*targetImage->ny;
                            DTYPE *targetPtrZ=&targetPtr[index];
                            int *maskPtrZ=&maskPtr[index];
						    for(int y=j*BLOCK_WIDTH; y<(j+1)*BLOCK_WIDTH; y++){
							    if(y<targetImage->ny){
                                    index = y*targetImage->nx+i*BLOCK_WIDTH;
                                    DTYPE *targetPtrXYZ=&targetPtrZ[index];
                                    int *maskPtrXYZ=&maskPtrZ[index];
								    for(int x=i*BLOCK_WIDTH; x<(i+1)*BLOCK_WIDTH; x++){
									    if(x<targetImage->nx){
										    targetValues[coord] = *targetPtrXYZ;
										    if(targetValues[coord]>0.0 && *maskPtrXYZ>-1){
											    mean += (float)targetValues[coord];
											    voxelNumber++;
										    }
									    }
                                        targetPtrXYZ++;
                                        maskPtrXYZ++;
                                        coord++;
								    }
							    }
						    }
					    }
				    }
				    if(voxelNumber>BLOCK_SIZE/2){
                        float variance=0.0f;
                        for(int i=0; i<BLOCK_SIZE; i++){
						    if(targetValues[coord]>0.0)
							    variance += (mean - (float)targetValues[i])
                                    * (mean - (float)targetValues[i]);
                        }
134

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
					    variance /= voxelNumber;
					    varianceArray[blockIndex]=variance;
				    }
				    else{
					    varianceArray[blockIndex]=-1;
					    unusableBlock++;
				    }
				    indexArray[blockIndex]=blockIndex;
				    blockIndex++;
			    }
		    }
	    }
    }
    else{
        // Version using 2D blocks
        for(int j=0; j<params->blockNumber[1]; j++){
            for(int i=0; i<params->blockNumber[0]; i++){
152

153
                memset(targetValues, 0, BLOCK_SIZE * sizeof(DTYPE));
154 155
                float mean=0.0f;
                float voxelNumber=0.0f;
156
                int coord=0;
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177

                for(int y=j*BLOCK_WIDTH; y<(j+1)*BLOCK_WIDTH; y++){
                    if(y<targetImage->ny){
                        index = y*targetImage->nx+i*BLOCK_WIDTH;
                        DTYPE *targetPtrXY=&targetPtr[index];
                        int *maskPtrXY=&maskPtr[index];
                        for(int x=i*BLOCK_WIDTH; x<(i+1)*BLOCK_WIDTH; x++){
                            if(x<targetImage->nx){
                                targetValues[coord] = *targetPtrXY;
                                if(targetValues[coord]>0.0 && *maskPtrXY>-1){
                                    mean += (float)targetValues[coord];
                                    voxelNumber++;
                                }
                            }
                            targetPtrXY++;
                            maskPtrXY++;
                            coord++;
                        }
                    }
                }
                if(voxelNumber>BLOCK_2D_SIZE/2){
178
                    float variance=0.0f;
179 180 181
                    for(int i=0; i<BLOCK_2D_SIZE; i++){
                        if(targetValues[coord]>0.0)
                            variance += (mean - (float)targetValues[i])
182 183 184
                                * (mean - (float)targetValues[i]);
                    }

185 186 187 188 189 190 191 192 193 194 195 196
                    variance /= voxelNumber;
                    varianceArray[blockIndex]=variance;
                }
                else{
                    varianceArray[blockIndex]=-1;
                    unusableBlock++;
                }
                indexArray[blockIndex]=blockIndex;
                blockIndex++;
            }
        }
    }
197
    free(targetValues);
198 199 200 201 202 203 204 205 206 207 208 209 210

	params->activeBlockNumber=params->activeBlockNumber<(totalBlockNumber-unusableBlock)?params->activeBlockNumber:(totalBlockNumber-unusableBlock);

	reg_heapSort(varianceArray, indexArray, totalBlockNumber);

	memset(params->activeBlock, 0, totalBlockNumber * sizeof(int));
	int *indexArrayPtr = &indexArray[totalBlockNumber-1];
	int count = 0;
	for(int i=0; i<params->activeBlockNumber; i++){
		params->activeBlock[*indexArrayPtr--] = count++;
	}
	for (int i = params->activeBlockNumber; i < totalBlockNumber; ++i){
		params->activeBlock[*indexArrayPtr--] = -1;
211
	}
212

213
    count = 0;
214 215
    if (runningOnGPU) {
        for(int i = 0; i < totalBlockNumber; ++i){
216
            if(params->activeBlock[i] != -1){
217
                params->activeBlock[i] = -1;
218
                params->activeBlock[count] = i;
219 220
                ++count;
            }
221
        }
222
    }
223

224 225
    free(varianceArray);
    free(indexArray);
226
}
227
/* *************************************************************** */
228 229 230 231
void initialise_block_matching_method(  nifti_image * target,
                                        _reg_blockMatchingParam *params,
                                        int percentToKeep_block,
                                        int percentToKeep_opt,
232 233
                                        int *mask,
                                        bool runningOnGPU)
234 235 236
{
	params->blockNumber[0]=(int)ceil((float)target->nx / (float)BLOCK_WIDTH);
	params->blockNumber[1]=(int)ceil((float)target->ny / (float)BLOCK_WIDTH);
237 238 239
    if(target->nz>1)
        params->blockNumber[2]=(int)ceil((float)target->nz / (float)BLOCK_WIDTH);
    else params->blockNumber[2]=1;
240 241 242 243 244 245 246

	params->percent_to_keep=percentToKeep_opt;
	params->activeBlockNumber=params->blockNumber[0]*params->blockNumber[1]*params->blockNumber[2] * percentToKeep_block / 100;

	params->activeBlock = (int *)malloc(params->blockNumber[0]*params->blockNumber[1]*params->blockNumber[2] * sizeof(int));
	switch(target->datatype){
		case NIFTI_TYPE_UINT8:
247
			_reg_set_active_blocks<unsigned char>(target, params, mask, runningOnGPU);break;
248
		case NIFTI_TYPE_INT8:
249
			_reg_set_active_blocks<char>(target, params, mask, runningOnGPU);break;
250
		case NIFTI_TYPE_UINT16:
251
			_reg_set_active_blocks<unsigned short>(target, params, mask, runningOnGPU);break;
252
		case NIFTI_TYPE_INT16:
253
			_reg_set_active_blocks<short>(target, params, mask, runningOnGPU);break;
254
		case NIFTI_TYPE_UINT32:
255
			_reg_set_active_blocks<unsigned int>(target, params, mask, runningOnGPU);break;
256
		case NIFTI_TYPE_INT32:
257
			_reg_set_active_blocks<int>(target, params, mask, runningOnGPU);break;
258
		case NIFTI_TYPE_FLOAT32:
259
			_reg_set_active_blocks<float>(target, params, mask, runningOnGPU);break;
260
		case NIFTI_TYPE_FLOAT64:
261
			_reg_set_active_blocks<double>(target, params, mask, runningOnGPU);break;
262 263 264 265
		default:
			fprintf(stderr,"ERROR\tinitialise_block_matching_method\tThe target image data type is not supported\n");
			return;
	}
266 267
#ifdef _VERBOSE
	printf("[VERBOSE]: There are %i active block(s) out of %i.\n", params->activeBlockNumber, params->blockNumber[0]*params->blockNumber[1]*params->blockNumber[2]);
268
#endif
269 270 271 272 273 274 275 276
    if(target->nz>1){
	    params->targetPosition = (float *)malloc(params->activeBlockNumber*3*sizeof(float));
	    params->resultPosition = (float *)malloc(params->activeBlockNumber*3*sizeof(float));
    }
    else{
        params->targetPosition = (float *)malloc(params->activeBlockNumber*2*sizeof(float));
        params->resultPosition = (float *)malloc(params->activeBlockNumber*2*sizeof(float));
    }
277 278
#ifdef _VERBOSE
	printf("[VERBOSE]: block matching initialisation done.\n");
279 280
#endif
}
281 282
/* *************************************************************** */
/* *************************************************************** */
283
template<typename PrecisionTYPE, typename TargetImageType, typename ResultImageType>
284
void block_matching_method2D(nifti_image * target,
285
                                nifti_image * result,
286 287
                                _reg_blockMatchingParam *params,
                                int *mask)
288
{
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
    TargetImageType *targetPtr=static_cast<TargetImageType *>(target->data);
    ResultImageType *resultPtr=static_cast<ResultImageType *>(result->data);

    TargetImageType *targetValues=(TargetImageType *)malloc(BLOCK_2D_SIZE*sizeof(TargetImageType));
    bool *targetOverlap=(bool *)malloc(BLOCK_2D_SIZE*sizeof(bool));
    ResultImageType *resultValues=(ResultImageType *)malloc(BLOCK_2D_SIZE*sizeof(ResultImageType));
    bool *resultOverlap=(bool *)malloc(BLOCK_2D_SIZE*sizeof(bool));

    mat44 *targetMatrix_xyz;
    if(target->sform_code >0)
        targetMatrix_xyz = &(target->sto_xyz);
    else targetMatrix_xyz = &(target->qto_xyz);

    int targetIndex_start_x;
    int targetIndex_start_y;
    int targetIndex_end_x;
    int targetIndex_end_y;
    int resultIndex_start_x;
    int resultIndex_start_y;
    int resultIndex_end_x;
    int resultIndex_end_y;

    unsigned int targetIndex;
    unsigned int resultIndex;

    unsigned int blockIndex=0;
    unsigned int activeBlockIndex=0;
316 317
    int index;

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
    for(int j=0; j<params->blockNumber[1]; j++){
        targetIndex_start_y=j*BLOCK_WIDTH;
        targetIndex_end_y=targetIndex_start_y+BLOCK_WIDTH;

        for(int i=0; i<params->blockNumber[0]; i++){
            targetIndex_start_x=i*BLOCK_WIDTH;
            targetIndex_end_x=targetIndex_start_x+BLOCK_WIDTH;

            if(params->activeBlock[blockIndex] > -1){

                targetIndex=0;
                memset(targetOverlap, 0, BLOCK_2D_SIZE*sizeof(bool));


                for(int y=targetIndex_start_y; y<targetIndex_end_y; y++){
                    if(-1<y && y<target->ny){
                        index = y*target->nx+targetIndex_start_x;
                        TargetImageType *targetPtr_XY = &targetPtr[index];
                        int *maskPtr_XY=&mask[index];
                        for(int x=targetIndex_start_x; x<targetIndex_end_x; x++){
                            if(-1<x && x<target->nx){
                                TargetImageType value = *targetPtr_XY;
                                if(value>0.0 && *maskPtr_XY>-1){
                                    targetValues[targetIndex]=value;
                                    targetOverlap[targetIndex]=1;
                                }
                            }
                            targetPtr_XY++;
                            maskPtr_XY++;
                            targetIndex++;
                        }
                    }
                    else targetIndex+=BLOCK_WIDTH;
                }
                PrecisionTYPE bestCC=0.0;
                float bestDisplacement[3] = {0.0f, 0.0f, 0.0f};

                // iteration over the result blocks
                for(int m=-OVERLAP_SIZE; m<=OVERLAP_SIZE; m+=STEP_SIZE){
                    resultIndex_start_y=targetIndex_start_y+m;
                    resultIndex_end_y=resultIndex_start_y+BLOCK_WIDTH;
                    for(int l=-OVERLAP_SIZE; l<=OVERLAP_SIZE; l+=STEP_SIZE){
                        resultIndex_start_x=targetIndex_start_x+l;
                        resultIndex_end_x=resultIndex_start_x+BLOCK_WIDTH;

                        resultIndex=0;
                        memset(resultOverlap, 0, BLOCK_2D_SIZE*sizeof(bool));

                        for(int y=resultIndex_start_y; y<resultIndex_end_y; y++){
                            if(-1<y && y<result->ny){
                                index=y*result->nx+resultIndex_start_x;
                                ResultImageType *resultPtr_XY = &resultPtr[index];
                                int *maskPtr_XY=&mask[index];
                                for(int x=resultIndex_start_x; x<resultIndex_end_x; x++){
                                    if(-1<x && x<result->nx){
                                        ResultImageType value = *resultPtr_XY;
                                        if(value>0.0 && *maskPtr_XY>-1){
                                            resultValues[resultIndex]=value;
                                            resultOverlap[resultIndex]=1;
                                        }
                                    }
                                    resultPtr_XY++;
                                    resultIndex++;
                                    maskPtr_XY++;
                                }
                            }
                            else resultIndex+=BLOCK_WIDTH;
                        }
                        PrecisionTYPE targetMean=0.0;
                        PrecisionTYPE resultMean=0.0;
                        PrecisionTYPE voxelNumber=0.0;
                        for(int a=0; a<BLOCK_2D_SIZE; a++){
                            if(targetOverlap[a] && resultOverlap[a]){
                                targetMean += (PrecisionTYPE)targetValues[a];
                                resultMean += (PrecisionTYPE)resultValues[a];
                                voxelNumber++;
                            }
                        }

                        if(voxelNumber>BLOCK_2D_SIZE/2){
                            targetMean /= voxelNumber;
                            resultMean /= voxelNumber;

                            PrecisionTYPE targetVar=0.0;
                            PrecisionTYPE resultVar=0.0;
                            PrecisionTYPE localCC=0.0;

                            for(int a=0; a<BLOCK_2D_SIZE; a++){
                                if(targetOverlap[a] && resultOverlap[a]){
                                    PrecisionTYPE targetTemp=(PrecisionTYPE)(targetValues[a]-targetMean);
                                    PrecisionTYPE resultTemp=(PrecisionTYPE)(resultValues[a]-resultMean);
                                    targetVar += (targetTemp)*(targetTemp);
                                    resultVar += (resultTemp)*(resultTemp);
                                    localCC += (targetTemp)*(resultTemp);
                                }
                            }

                            localCC = fabs(localCC/sqrt(targetVar*resultVar));

                            if(localCC>bestCC){
                                bestCC=localCC;
                                bestDisplacement[0] = (float)l;
                                bestDisplacement[1] = (float)m;
                            }
                        } 
                    }
                }

                    float targetPosition_temp[3];
                    targetPosition_temp[0] = (float)(i*BLOCK_WIDTH);
                    targetPosition_temp[1] = (float)(j*BLOCK_WIDTH);
                    targetPosition_temp[2] = 0.0f;

                    bestDisplacement[0] += targetPosition_temp[0];
                    bestDisplacement[1] += targetPosition_temp[1];
                    bestDisplacement[2] = 0.0f;

                    float tempPosition[3];
                    apply_affine(targetMatrix_xyz, targetPosition_temp, tempPosition);
                    params->targetPosition[activeBlockIndex] = tempPosition[0];
                    params->targetPosition[activeBlockIndex+1] = tempPosition[1];
                    apply_affine(targetMatrix_xyz, bestDisplacement, tempPosition);
                    params->resultPosition[activeBlockIndex] = tempPosition[0];
                    params->resultPosition[activeBlockIndex+1] = tempPosition[1];
442
                    activeBlockIndex += 2;
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
            }
            blockIndex++;
        }
    }
    free(resultValues);
    free(targetValues);
    free(targetOverlap);
    free(resultOverlap);
}
/* *************************************************************** */
template<typename PrecisionTYPE, typename TargetImageType, typename ResultImageType>
void block_matching_method3D(nifti_image * target,
                                nifti_image * result,
                                _reg_blockMatchingParam *params,
                                int *mask)
{
    TargetImageType *targetPtr=static_cast<TargetImageType *>(target->data);
    ResultImageType *resultPtr=static_cast<ResultImageType *>(result->data);

    TargetImageType *targetValues=(TargetImageType *)malloc(BLOCK_SIZE*sizeof(TargetImageType));
    bool *targetOverlap=(bool *)malloc(BLOCK_SIZE*sizeof(bool));
    ResultImageType *resultValues=(ResultImageType *)malloc(BLOCK_SIZE*sizeof(ResultImageType));
    bool *resultOverlap=(bool *)malloc(BLOCK_SIZE*sizeof(bool));

    mat44 *targetMatrix_xyz;
    if(target->sform_code >0)
        targetMatrix_xyz = &(target->sto_xyz);
    else targetMatrix_xyz = &(target->qto_xyz);

    int targetIndex_start_x;
    int targetIndex_start_y;
    int targetIndex_start_z;
    int targetIndex_end_x;
    int targetIndex_end_y;
    int targetIndex_end_z;
    int resultIndex_start_x;
    int resultIndex_start_y;
    int resultIndex_start_z;
    int resultIndex_end_x;
    int resultIndex_end_y;
    int resultIndex_end_z;

    unsigned int targetIndex;
    unsigned int resultIndex;

    unsigned int blockIndex=0;
    unsigned int activeBlockIndex=0;
    int index;

    for(int k=0; k<params->blockNumber[2]; k++){
        targetIndex_start_z=k*BLOCK_WIDTH;
        targetIndex_end_z=targetIndex_start_z+BLOCK_WIDTH;
495

496 497 498
        for(int j=0; j<params->blockNumber[1]; j++){
            targetIndex_start_y=j*BLOCK_WIDTH;
            targetIndex_end_y=targetIndex_start_y+BLOCK_WIDTH;
499

500 501 502
            for(int i=0; i<params->blockNumber[0]; i++){
                targetIndex_start_x=i*BLOCK_WIDTH;
                targetIndex_end_x=targetIndex_start_x+BLOCK_WIDTH;
503

504 505 506 507 508
                if(params->activeBlock[blockIndex] > -1){
                    targetIndex=0;
                    memset(targetOverlap, 0, BLOCK_SIZE*sizeof(bool));
                    for(int z=targetIndex_start_z; z<targetIndex_end_z; z++){
                        if(-1<z && z<target->nz){
509
                            index = z*target->nx*target->ny;
510
                            TargetImageType *targetPtr_Z = &targetPtr[index];
511
                            int *maskPtr_Z=&mask[index];
512 513
                            for(int y=targetIndex_start_y; y<targetIndex_end_y; y++){
                                if(-1<y && y<target->ny){
514
                                    index = y*target->nx+targetIndex_start_x;
515
                                    TargetImageType *targetPtr_XYZ = &targetPtr_Z[index];
516
                                    int *maskPtr_XYZ=&maskPtr_Z[index];
517 518 519 520 521 522 523 524 525
                                    for(int x=targetIndex_start_x; x<targetIndex_end_x; x++){
                                        if(-1<x && x<target->nx){
                                            TargetImageType value = *targetPtr_XYZ;
                                            if(value>0.0 && *maskPtr_XYZ>-1){
                                                targetValues[targetIndex]=value;
                                                targetOverlap[targetIndex]=1;
                                            }
                                        }
                                        targetPtr_XYZ++;
526
                                        maskPtr_XYZ++;
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
                                        targetIndex++;
                                    }
                                }
                                else targetIndex+=BLOCK_WIDTH;
                            }
                        }
                        else targetIndex+=BLOCK_WIDTH*BLOCK_WIDTH;
                    }
                    PrecisionTYPE bestCC=0.0;
                    float bestDisplacement[3] = {0.0f, 0.0f, 0.0f};
    
                    // iteration over the result blocks
                    for(int n=-OVERLAP_SIZE; n<=OVERLAP_SIZE; n+=STEP_SIZE){
                        resultIndex_start_z=targetIndex_start_z+n;
                        resultIndex_end_z=resultIndex_start_z+BLOCK_WIDTH;
                        for(int m=-OVERLAP_SIZE; m<=OVERLAP_SIZE; m+=STEP_SIZE){
                            resultIndex_start_y=targetIndex_start_y+m;
                            resultIndex_end_y=resultIndex_start_y+BLOCK_WIDTH;
                            for(int l=-OVERLAP_SIZE; l<=OVERLAP_SIZE; l+=STEP_SIZE){
                                resultIndex_start_x=targetIndex_start_x+l;
                                resultIndex_end_x=resultIndex_start_x+BLOCK_WIDTH;

                                resultIndex=0;
                                memset(resultOverlap, 0, BLOCK_SIZE*sizeof(bool));

                                for(int z=resultIndex_start_z; z<resultIndex_end_z; z++){
                                    if(-1<z && z<result->nz){
554 555 556
                                        index = z*result->nx*result->ny;
                                        ResultImageType *resultPtr_Z = &resultPtr[index];
                                        int *maskPtr_Z = &mask[index];
557 558
                                        for(int y=resultIndex_start_y; y<resultIndex_end_y; y++){
                                            if(-1<y && y<result->ny){
559
                                                index=y*result->nx+resultIndex_start_x;
560
                                                ResultImageType *resultPtr_XYZ = &resultPtr_Z[index];
561
                                                int *maskPtr_XYZ=&maskPtr_Z[index];
562 563 564 565 566 567 568 569 570
                                                for(int x=resultIndex_start_x; x<resultIndex_end_x; x++){
                                                    if(-1<x && x<result->nx){
                                                        ResultImageType value = *resultPtr_XYZ;
                                                        if(value>0.0 && *maskPtr_XYZ>-1){
                                                            resultValues[resultIndex]=value;
                                                            resultOverlap[resultIndex]=1;
                                                        }
                                                    }
                                                    resultPtr_XYZ++;
571 572
                                                    resultIndex++;
                                                    maskPtr_XYZ++;
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
                                                }
                                            }
                                            else resultIndex+=BLOCK_WIDTH;
                                        }
                                    }
                                    else resultIndex+=BLOCK_WIDTH*BLOCK_WIDTH;
                                }
                                PrecisionTYPE targetMean=0.0;
                                PrecisionTYPE resultMean=0.0;
                                PrecisionTYPE voxelNumber=0.0;
                                for(int a=0; a<BLOCK_SIZE; a++){
                                    if(targetOverlap[a] && resultOverlap[a]){
                                        targetMean += (PrecisionTYPE)targetValues[a];
                                        resultMean += (PrecisionTYPE)resultValues[a];
                                        voxelNumber++;
                                    }
                                }
    
591
                                if(voxelNumber>BLOCK_SIZE/2){
592 593 594
                                    targetMean /= voxelNumber;
                                    resultMean /= voxelNumber;
    
595 596 597 598
                                    PrecisionTYPE targetVar=0.0;
                                    PrecisionTYPE resultVar=0.0;
                                    PrecisionTYPE localCC=0.0;

599 600 601 602 603 604 605 606 607 608
                                    for(int a=0; a<BLOCK_SIZE; a++){
                                        if(targetOverlap[a] && resultOverlap[a]){
                                            PrecisionTYPE targetTemp=(PrecisionTYPE)(targetValues[a]-targetMean);
                                            PrecisionTYPE resultTemp=(PrecisionTYPE)(resultValues[a]-resultMean);
                                            targetVar += (targetTemp)*(targetTemp);
                                            resultVar += (resultTemp)*(resultTemp);
                                            localCC += (targetTemp)*(resultTemp);
                                        }
                                    }
    
609
                                    localCC = fabs(localCC/sqrt(targetVar*resultVar));
610 611 612 613 614 615 616 617 618 619 620
    
                                    if(localCC>bestCC){                                        
                                        bestCC=localCC;
                                        bestDisplacement[0] = (float)l;
                                        bestDisplacement[1] = (float)m;
                                        bestDisplacement[2] = (float)n;
                                    }
                                } 
                            }
                        }
                    }
621

622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
                    float targetPosition_temp[3];
                    targetPosition_temp[0] = (float)(i*BLOCK_WIDTH);
                    targetPosition_temp[1] = (float)(j*BLOCK_WIDTH);
                    targetPosition_temp[2] = (float)(k*BLOCK_WIDTH);

                    bestDisplacement[0] += targetPosition_temp[0];
                    bestDisplacement[1] += targetPosition_temp[1];
                    bestDisplacement[2] += targetPosition_temp[2];

                    float tempPosition[3];
                    apply_affine(targetMatrix_xyz, targetPosition_temp, tempPosition);
                    params->targetPosition[activeBlockIndex] = tempPosition[0];
                    params->targetPosition[activeBlockIndex+1] = tempPosition[1];
                    params->targetPosition[activeBlockIndex+2] = tempPosition[2];
                    apply_affine(targetMatrix_xyz, bestDisplacement, tempPosition);
                    params->resultPosition[activeBlockIndex] = tempPosition[0];
                    params->resultPosition[activeBlockIndex+1] = tempPosition[1];
                    params->resultPosition[activeBlockIndex+2] = tempPosition[2];
                    activeBlockIndex += 3;
                }
                blockIndex++;
            }
        }
    }
    free(resultValues);
    free(targetValues);
    free(targetOverlap);
649
    free(resultOverlap);
650
}
651
/* *************************************************************** */
652 653
// Called internally to determine the parameter type
template<typename PrecisionTYPE, typename TargetImageType> 
654
void block_matching_method2(   nifti_image * target,
655 656 657 658
                                nifti_image * result,
                                _reg_blockMatchingParam *params,
                                int *mask)
{
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
    if(target->nz==1){
        switch(result->datatype){
            case NIFTI_TYPE_UINT8:
                block_matching_method2D<PrecisionTYPE, TargetImageType, unsigned char>
                        (target, result, params, mask);
                        break;
            case NIFTI_TYPE_INT8:
                block_matching_method2D<PrecisionTYPE, TargetImageType, char>
                        (target, result, params, mask);
                        break;
            case NIFTI_TYPE_UINT16:
                block_matching_method2D<PrecisionTYPE, TargetImageType, unsigned short>
                        (target, result, params, mask);
                        break;
            case NIFTI_TYPE_INT16:
                block_matching_method2D<PrecisionTYPE, TargetImageType, short>
                        (target, result, params, mask);
                        break;
            case NIFTI_TYPE_UINT32:
                block_matching_method2D<PrecisionTYPE, TargetImageType, unsigned int>
                        (target, result, params, mask);
                        break;
            case NIFTI_TYPE_INT32:
                block_matching_method2D<PrecisionTYPE, TargetImageType, int>
                        (target, result, params, mask);
                        break;
            case NIFTI_TYPE_FLOAT32:
                block_matching_method2D<PrecisionTYPE, TargetImageType, float>
                        (target, result, params, mask);
                        break;
            case NIFTI_TYPE_FLOAT64:
                block_matching_method2D<PrecisionTYPE, TargetImageType, double>
                        (target, result, params, mask);
                        break;
            default:
                printf("err\tblock_match\tThe target image data type is not "
                        "supported\n");
                return;
        }
    }
    else{
        switch(result->datatype){
            case NIFTI_TYPE_UINT8:
                block_matching_method3D<PrecisionTYPE, TargetImageType, unsigned char>
                        (target, result, params, mask);
                        break;
            case NIFTI_TYPE_INT8:
                block_matching_method3D<PrecisionTYPE, TargetImageType, char>
                        (target, result, params, mask);
                        break;
            case NIFTI_TYPE_UINT16:
                block_matching_method3D<PrecisionTYPE, TargetImageType, unsigned short>
                        (target, result, params, mask);
                        break;
            case NIFTI_TYPE_INT16:
                block_matching_method3D<PrecisionTYPE, TargetImageType, short>
                        (target, result, params, mask);
                        break;
            case NIFTI_TYPE_UINT32:
                block_matching_method3D<PrecisionTYPE, TargetImageType, unsigned int>
                        (target, result, params, mask);
                        break;
            case NIFTI_TYPE_INT32:
                block_matching_method3D<PrecisionTYPE, TargetImageType, int>
                        (target, result, params, mask);
                        break;
            case NIFTI_TYPE_FLOAT32:
                block_matching_method3D<PrecisionTYPE, TargetImageType, float>
                        (target, result, params, mask);
                        break;
            case NIFTI_TYPE_FLOAT64:
                block_matching_method3D<PrecisionTYPE, TargetImageType, double>
                        (target, result, params, mask);
                        break;
            default:
                printf("err\tblock_match\tThe target image data type is not "
                        "supported\n");
                return;
        }
738 739
    }
}
740
/* *************************************************************** */
741 742
// Block matching interface function
template<typename PrecisionTYPE>
743 744 745 746
void block_matching_method(	nifti_image * target,
							nifti_image * result,
							_reg_blockMatchingParam *params,
                            int *mask)
747 748 749
{
	switch(target->datatype){
		case NIFTI_TYPE_UINT8:
750
			block_matching_method2<PrecisionTYPE, unsigned char>
751
					(target, result, params, mask);
752 753
					break;
		case NIFTI_TYPE_INT8:
754
			block_matching_method2<PrecisionTYPE, char>
755
					(target, result, params, mask);
756 757
					break;
		case NIFTI_TYPE_UINT16:
758
			block_matching_method2<PrecisionTYPE, unsigned short>
759
					(target, result, params, mask);
760 761
					break;
		case NIFTI_TYPE_INT16:
762
			block_matching_method2<PrecisionTYPE, short>
763
					(target, result, params, mask);
764 765
					break;
		case NIFTI_TYPE_UINT32:
766
			block_matching_method2<PrecisionTYPE, unsigned int>
767
					(target, result, params, mask);
768 769
					break;
		case NIFTI_TYPE_INT32:
770
			block_matching_method2<PrecisionTYPE, int>
771
					(target, result, params, mask);
772 773
					break;
		case NIFTI_TYPE_FLOAT32:
774
			block_matching_method2<PrecisionTYPE, float>
775
					(target, result, params, mask);
776 777
					break;
		case NIFTI_TYPE_FLOAT64:
778
			block_matching_method2<PrecisionTYPE, double>
779
					(target, result, params, mask);
780 781 782 783 784 785 786
					break;
		default:
			printf("err\tblock_match\tThe target image data type is not"
					"supported\n");
			return;
	}
}
787 788
template void block_matching_method<float>(nifti_image *, nifti_image *, _reg_blockMatchingParam *, int *);
template void block_matching_method<double>(nifti_image *, nifti_image *, _reg_blockMatchingParam *, int *);
789 790
/* *************************************************************** */
/* *************************************************************** */
791 792 793

// Apply the suppled affine transformation to a 3D point
void apply_affine(mat44 * mat, float *pt, float *result)
794 795 796 797 798 799 800 801 802
{   
    result[0] = (mat->m[0][0] * pt[0]) + (mat->m[0][1]*pt[1]) + (mat->m[0][2]*pt[2]) + (mat->m[0][3]);
    result[1] = (mat->m[1][0] * pt[0]) + (mat->m[1][1]*pt[1]) + (mat->m[1][2]*pt[2]) + (mat->m[1][3]);
    result[2] = (mat->m[2][0] * pt[0]) + (mat->m[2][1]*pt[1]) + (mat->m[2][2]*pt[2]) + (mat->m[2][3]);
}
void apply_affine2D(mat44 * mat, float *pt, float *result)
{   
    result[0] = (mat->m[0][0] * pt[0]) + (mat->m[0][1]*pt[1]) + (mat->m[0][3]);
    result[1] = (mat->m[1][0] * pt[0]) + (mat->m[1][1]*pt[1]) + (mat->m[1][3]);
803 804
}

805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
struct _reg_sorted_point3D
{
    float target[3];
    float result[3];

    double distance;

    _reg_sorted_point3D(float * t, float * r, double d)
        :distance(d)
    {
        target[0] = t[0];
        target[1] = t[1];
        target[2] = t[2];
        
        result[0] = r[0];
        result[1] = r[1];
        result[2] = r[2];
    }
     
    const bool operator <(const _reg_sorted_point3D & sp) const
    {
        return (sp.distance < distance);
    }
};
struct _reg_sorted_point2D
{
    float target[2];
    float result[2];
833

834
    double distance;
835

836 837 838 839 840 841 842 843 844 845 846 847 848
    _reg_sorted_point2D(float * t, float * r, double d)
        :distance(d)
    {
        target[0] = t[0];
        target[1] = t[1];

        result[0] = r[0];
        result[1] = r[1];
    }
    const bool operator <(const _reg_sorted_point2D & sp) const
    {
        return (sp.distance < distance);
    }
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
};

// Multiply matrices A and B together and store the result in r.
// We assume that the input pointers are valid and can store the result.
// A = ar * ac
// B = ac * bc
// r = ar * bc

// We can specify if we want to multiply A with the transpose of B

void mul_matrices(float ** a, float ** b, int ar, int ac, int bc, float ** r, bool transposeB)
{
	if (transposeB){
		for (int i = 0; i < ar; ++i){
			for (int j = 0; j < bc; ++j){
				r[i][j] = 0.0f;
				for (int k = 0; k < ac; ++k){
					r[i][j] += a[i][k] * b[j][k];
				}
			}
		}
	}
	else{		
		for (int i = 0; i < ar; ++i){
			for (int j = 0; j < bc; ++j){
				r[i][j] = 0.0f;
				for (int k = 0; k < ac; ++k){
					r[i][j] += a[i][k] * b[k][j];
				}
			}
		}
	}
}

// Multiply a matrix with a vctor
void mul_matvec(float ** a, int ar, int ac, float * b, float * r)
{
	for (int i = 0; i < ar; ++i){
		r[i] = 0;
		for (int k = 0; k < ac; ++k){
			r[i] += a[i][k] * b[k];
		}
	}
}

// Compute determinant of a 3x3 matrix
float compute_determinant3x3(float ** mat)
{
	return 	(mat[0][0]*(mat[1][1]*mat[2][2]-mat[1][2]*mat[2][1]))-
			(mat[0][1]*(mat[1][0]*mat[2][2]-mat[1][2]*mat[2][0]))+
			(mat[0][2]*(mat[1][0]*mat[2][1]-mat[1][1]*mat[2][0]));
}

// estimate an affine transformation using least square
903
void estimate_affine_transformation3D(std::vector<_reg_sorted_point3D> & points,
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
									mat44 * transformation,
									float ** A,
									float *  w,
									float ** v,
									float ** r,
									float *  b)
{	
	// Create our A matrix
	// Each point will give us 3 linearly independent equations, so
	// we need at least 4 points. Assuming we have that here.
	int num_equations = points.size() * 3;
	unsigned c = 0;
	for (unsigned k = 0; k < points.size(); ++k)
	{
		c = k * 3;
		A[c][0] = points[k].target[0];
		A[c][1] = points[k].target[1];
		A[c][2] = points[k].target[2];
		A[c][3] = A[c][4] = A[c][5] = A[c][6] = A[c][7] = A[c][8] = A[c][10] = A[c][11] = 0.0f;
		A[c][9] = 1.0;
			
		A[c+1][3] = points[k].target[0];
		A[c+1][4] = points[k].target[1];
		A[c+1][5] = points[k].target[2];
		A[c+1][0] = A[c+1][1] = A[c+1][2] = A[c+1][6] = A[c+1][7] = A[c+1][8] = A[c+1][9] = A[c+1][11] = 0.0f;
		A[c+1][10] = 1.0;
			
		A[c+2][6] = points[k].target[0];
		A[c+2][7] = points[k].target[1];
		A[c+2][8] = points[k].target[2];
		A[c+2][0] = A[c+2][1] = A[c+2][2] = A[c+2][3] = A[c+2][4] = A[c+2][5] = A[c+2][9] = A[c+2][10] = 0.0f;
		A[c+2][11] = 1.0;
	}	
	
	for (unsigned k = 0; k < 12; ++k)
	{
		w[k] = 0.0f;
	}	
942
	// Now we can compute our svd
943 944
	svd(A, num_equations, 12, w, v);
		
945 946 947
	// First we make sure that the really small singular values
	// are set to 0. and compute the inverse by taking the reciprocal
	// of the entries
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
	for (unsigned k = 0; k < 12; ++k)
	{
		if (w[k] < 0.0001)
		{
			w[k] = 0.0f;
		}
		else
		{
			w[k] = 1.0f/w[k];
		}
	}
		
	// Now we can compute the pseudoinverse which is given by
	// V*inv(W)*U'
	// First compute the V * inv(w) in place.
	// Simply scale each column by the corresponding singular value 
	for (unsigned k = 0; k < 12; ++k)
	{
		for (unsigned j = 0; j < 12; ++j)
		{
			v[j][k] *=w[k];
		}
	}
		
	// Now multiply the matrices together
	// Pseudoinverse = v * e * A(transpose)
	mul_matrices(v, A, 12, 12, num_equations, r, true);		
	// Now r contains the pseudoinverse
	// Create vector b and then multiple rb to get the affine paramsA
	for (unsigned k = 0; k < points.size(); ++k)
	{
		c = k * 3;			 
		b[c] = 		points[k].result[0];
		b[c+1] = 	points[k].result[1];
		b[c+2] = 	points[k].result[2];
	}
		
	float * transform = new float[12];
	mul_matvec(r, 12, num_equations, b, transform);
	
	transformation->m[0][0] = transform[0];
	transformation->m[0][1] = transform[1];
	transformation->m[0][2] = transform[2];
	transformation->m[0][3] = transform[9];
		
	transformation->m[1][0] = transform[3];
	transformation->m[1][1] = transform[4];
	transformation->m[1][2] = transform[5];
	transformation->m[1][3] = transform[10];
		
	transformation->m[2][0] = transform[6];
	transformation->m[2][1] = transform[7];
	transformation->m[2][2] = transform[8];
	transformation->m[2][3] = transform[11];
		
	transformation->m[3][0] = 0.0f;
	transformation->m[3][1] = 0.0f;
	transformation->m[3][2] = 0.0f;
	transformation->m[3][3] = 1.0f;

	delete[] transform;
}

1011
void optimize_affine3D(	_reg_blockMatchingParam *params,
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
						mat44 * final)
{
	// Set the current transformation to identity
	final->m[0][0] = final->m[1][1] = final->m[2][2] = final->m[3][3] = 1.0f;
	final->m[0][1] = final->m[0][2] = final->m[0][3] = 0.0f;
	final->m[1][0] = final->m[1][2] = final->m[1][3] = 0.0f;
	final->m[2][0] = final->m[2][1] = final->m[2][3] = 0.0f;
	final->m[3][0] = final->m[3][1] = final->m[3][2] = 0.0f;

	const unsigned num_points = params->activeBlockNumber;
	unsigned long num_equations = num_points * 3;
1023 1024
	std::priority_queue<_reg_sorted_point3D> queue;
	std::vector<_reg_sorted_point3D> top_points;
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
	double distance = 0.0;
	double lastDistance = 0.0;
	unsigned long i;

	// massive left hand side matrix
	float ** a = new float *[num_equations];
	for (unsigned k = 0; k < num_equations; ++k)
	{			
		a[k] = new float[12]; // full affine
	}
	
	// The array of singular values returned by svd
	float *w = new float[12];
		
	// v will be n x n
	float **v = new float *[12];
	for (unsigned k = 0; k < 12; ++k)
	{
		v[k] = new float[12];
	}
	
	// Allocate memory for pseudoinverse		
	float **r = new float *[12];
	for (unsigned k = 0; k < 12; ++k)
	{
		r[k] = new float[num_equations];
	}
	
	// Allocate memory for RHS vector
	float *b = new float[num_equations];
	
	// The initial vector with all the input points
	for (unsigned j = 0; j < num_points*3; j+=3)
	{
1059
		top_points.push_back(_reg_sorted_point3D(&(params->targetPosition[j]), 
1060 1061 1062 1063
							 &(params->resultPosition[j]),0.0f));
	}
	
	// estimate the optimal transformation while considering all the points
1064
	estimate_affine_transformation3D(top_points, final, a, w, v, r, b);
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110

	// Delete a, b and r. w and v will not change size in subsequent svd operations.
	for (unsigned int k = 0; k < num_equations; ++k)
	{
		delete[] a[k];
	}
	delete[] a;
	delete[] b;
	
	for (unsigned k = 0; k < 12; ++k)
	{
		delete[] r[k];
	}
	delete [] r;


	// The LS in the iterations is done on subsample of the input data	
	float * newResultPosition = new float[num_points*3];
	const unsigned long num_to_keep = (unsigned long)(num_points * (params->percent_to_keep/100.0f));
	num_equations = num_to_keep*3;

	// The LHS matrix
	a = new float *[num_equations];
	for (unsigned k = 0; k < num_equations; ++k)
	{			
		a[k] = new float[12]; // full affine
	}
	
	// Allocate memory for pseudoinverse		
	r = new float *[12];
	for (unsigned k = 0; k < 12; ++k)
	{
		r[k] = new float[num_equations];
	}
	
	// Allocate memory for RHS vector
	b = new float[num_equations];
	
	for (unsigned count = 0; count < MAX_ITERATIONS; ++count)
	{
		// Transform the points in the target
		for (unsigned j = 0; j < num_points * 3; j+=3)		
		{				
			apply_affine(final, &(params->targetPosition[j]), &newResultPosition[j]);
		}

1111
		queue = std::priority_queue<_reg_sorted_point3D> ();
1112 1113 1114
		for (unsigned j = 0; j < num_points * 3; j+=3)
		{
			distance = get_square_distance(&newResultPosition[j], &(params->resultPosition[j]));
1115
			queue.push(_reg_sorted_point3D(&(params->targetPosition[j]), 
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
					   &(params->resultPosition[j]), distance));
		}
						
		distance = 0.0;	
		i = 0;
		top_points.clear();
		while (i < num_to_keep && i < queue.size())
		{
			top_points.push_back(queue.top());
			distance += queue.top().distance;
			queue.pop();
			++i;
		}
				
1130
		// If the change is not substantial, we return 
1131
		if (fabs(distance - lastDistance) < TOLERANCE)
1132
		{
1133
			break;
1134
		}
1135 1136
		
		lastDistance = distance;
1137
		estimate_affine_transformation3D(top_points, final, a, w, v, r, b);	
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
	}
	
	delete[] newResultPosition;
	delete[] b;
	for (unsigned k = 0; k < 12; ++k)
	{
		delete[] r[k];
	}
	delete [] r;
				
	// free the memory
	for (unsigned int k = 0; k < num_equations; ++k)
	{
		delete[] a[k];
	}
	delete[] a;
		
	delete[] w;
	for (int k = 0; k < 12; ++k)
	{
		delete[] v[k];
	}
	delete [] v;	
}
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
void estimate_rigid_transformation2D(  std::vector<_reg_sorted_point2D> & points,
                                        mat44 * transformation)
{
    float centroid_target[2] = {0.0f};
    float centroid_result[2] = {0.0f};

    for (unsigned j = 0; j < points.size(); ++j){
        centroid_target[0] += points[j].target[0];
        centroid_target[1] += points[j].target[1];
        centroid_result[0] += points[j].result[0];
        centroid_result[1] += points[j].result[1];
    }

    centroid_target[0] /= (float)(points.size());
    centroid_target[1] /= (float)(points.size());

    centroid_result[0] /= (float)(points.size());
    centroid_result[1] /= (float)(points.size());

    float ** u = new float*[2];
    float * w = new float[2];
    float ** v = new float*[2];
    float ** ut = new float*[2];
    float ** r = new float*[2];

    for (unsigned i = 0; i < 2; ++i){
        u[i] = new float[2];
        v[i] = new float[2];
        ut[i] = new float[2];
        r[i] = new float[2];
        w[i] = 0.0f;
        for (unsigned j = 0; j < 2; ++j){
            u[i][j] = v[i][j] = ut[i][j] = r[i][j] = 0.0f;
        }
    }

    // Demean the input points
    for (unsigned j = 0; j < points.size(); ++j){
        points[j].target[0] -= centroid_target[0];
        points[j].target[1] -= centroid_target[1];

        points[j].result[0] -= centroid_result[0];
        points[j].result[1] -= centroid_result[1];

        u[0][0] += points[j].target[0] * points[j].result[0];
        u[0][1] += points[j].target[0] * points[j].result[1];

        u[1][0] += points[j].target[1] * points[j].result[0];
        u[1][1] += points[j].target[1] * points[j].result[1];
    }

    svd(u, 2, 2, w, v);
1214

1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
    // Calculate transpose  
    ut[0][0] = u[0][0]; 
    ut[1][0] = u[0][1];

    ut[0][1] = u[1][0];
    ut[1][1] = u[1][1];

    // Calculate the rotation matrix
    mul_matrices(v, ut, 2, 2, 2, r, false);

    float det = (r[0][0] * r[1][1]) - (r[0][1] * r[1][0]);

    // Take care of possible reflection 
    if (det < 0.0f)
    {
        v[0][2] = -v[0][2];
        v[1][2] = -v[1][2];
        mul_matrices(v, ut, 2, 2, 2, r, false);
    }

    // Calculate the translation
    float t[2];
    t[0] = centroid_result[0] - (r[0][0] * centroid_target[0] +
    r[0][1] * centroid_target[1]);

    t[1] = centroid_result[1] - (r[1][0] * centroid_target[0] +
    r[1][1] * centroid_target[1]);

    transformation->m[0][0] = r[0][0];
    transformation->m[0][1] = r[0][1];
    transformation->m[0][3] = t[0];

    transformation->m[1][0] = r[1][0];
    transformation->m[1][1] = r[1][1];
    transformation->m[1][3] = t[1];

    transformation->m[2][0] = 0.0f;
    transformation->m[2][1] = 0.0f;
    transformation->m[2][2] = 1.0f;
    transformation->m[2][3] = 0.0f;

    transformation->m[0][2] = 0.0f;
    transformation->m[1][2] = 0.0f;
    transformation->m[3][2] = 0.0f;

    transformation->m[3][0] = 0.0f;
    transformation->m[3][1] = 0.0f;
    transformation->m[3][2] = 0.0f;
    transformation->m[3][3] = 1.0f;

    // Do the deletion here
    for (int i = 0; i < 2; ++i)
    {
        delete [] u[i];
        delete [] v[i];
        delete [] ut[i];
        delete [] r[i];
    }
    delete [] u;
    delete [] v;
    delete [] ut;
    delete [] r;
    delete [] w;
}
void estimate_rigid_transformation3D(std::vector<_reg_sorted_point3D> & points,
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
								   mat44 * transformation)
{	
	float centroid_target[3] = {0.0f};
	float centroid_result[3] = {0.0f};
	
	
	for (unsigned j = 0; j < points.size(); ++j)
	{
		centroid_target[0] += points[j].target[0];
		centroid_target[1] += points[j].target[1];
		centroid_target[2] += points[j].target[2];
			
		centroid_result[0] += points[j].result[0];
		centroid_result[1] += points[j].result[1];
		centroid_result[2] += points[j].result[2];
	}
		
	centroid_target[0] /= (float)(points.size());
	centroid_target[1] /= (float)(points.size());
	centroid_target[2] /= (float)(points.size());
	
	centroid_result[0] /= (float)(points.size());
	centroid_result[1] /= (float)(points.size());
	centroid_result[2] /= (float)(points.size());
	
	float ** u = new float*[3];
	float * w = new float[3];
	float ** v = new float*[3];
	float ** ut = new float*[3];
	float ** r = new float*[3];

	for (unsigned i = 0; i < 3; ++i)
	{
		u[i] = new float[3];
		v[i] = new float[3];
		ut[i] = new float[3];
		r[i] = new float[3];
		
		w[i] = 0.0f;
	
		
		for (unsigned j = 0; j < 3; ++j)
		{
			u[i][j] = v[i][j] = ut[i][j] = r[i][j] = 0.0f;			
		}
	}
	
	// Demean the input points
	for (unsigned j = 0; j < points.size(); ++j)
	{
		points[j].target[0] -= centroid_target[0];
		points[j].target[1] -= centroid_target[1];
		points[j].target[2] -= centroid_target[2];
			
		points[j].result[0] -= centroid_result[0];
		points[j].result[1] -= centroid_result[1];
		points[j].result[2] -= centroid_result[2];
			
		u[0][0] += points[j].target[0] * points[j].result[0];
		u[0][1] += points[j].target[0] * points[j].result[1];
		u[0][2] += points[j].target[0] * points[j].result[2];
			
		u[1][0] += points[j].target[1] * points[j].result[0];
		u[1][1] += points[j].target[1] * points[j].result[1];
		u[1][2] += points[j].target[1] * points[j].result[2];
			
		u[2][0] += points[j].target[2] * points[j].result[0];
		u[2][1] += points[j].target[2] * points[j].result[1];
		u[2][2] += points[j].target[2] * points[j].result[2];
		
	}
	
	svd(u, 3, 3, w, v);	
	
	// Calculate transpose	
	ut[0][0] = u[0][0];	
	ut[1][0] = u[0][1];
	ut[2][0] = u[0][2];
	
	ut[0][1] = u[1][0];
	ut[1][1] = u[1][1];
	ut[2][1] = u[1][2];
	
	ut[0][2] = u[2][0];
	ut[1][2] = u[2][1];
	ut[2][2] = u[2][2];
	
	// Calculate the rotation matrix
	mul_matrices(v, ut, 3, 3, 3, r, false);
	
	float det = compute_determinant3x3(r);
	
	// Take care of possible reflection 
	if (det < 0.0f)
	{
		v[0][2] = -v[0][2];
		v[1][2] = -v[1][2];
		v[2][2] = -v[2][2];
		
	}
		// Calculate the rotation matrix
	mul_matrices(v, ut, 3, 3, 3, r, false);
	
	// Calculate the translation
	float t[3];
	t[0] = centroid_result[0] - (r[0][0] * centroid_target[0] +
	r[0][1] * centroid_target[1] +
	r[0][2] * centroid_target[2]);
	
	t[1] = centroid_result[1] - (r[1][0] * centroid_target[0] +
	r[1][1] * centroid_target[1] +
	r[1][2] * centroid_target[2]);
	
	t[2] = centroid_result[2] - (r[2][0] * centroid_target[0] +
	r[2][1] * centroid_target[1] +
1395
	r[2][2] * centroid_target[2]);	
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
		
	transformation->m[0][0] = r[0][0];
	transformation->m[0][1] = r[0][1];
	transformation->m[0][2] = r[0][2];
	transformation->m[0][3] = t[0];	
		
	transformation->m[1][0] = r[1][0];
	transformation->m[1][1] = r[1][1];
	transformation->m[1][2] = r[1][2];
	transformation->m[1][3] = t[1];
		
	transformation->m[2][0] = r[2][0];
	transformation->m[2][1] = r[2][1];
	transformation->m[2][2] = r[2][2];
	transformation->m[2][3] = t[2];
		
	transformation->m[3][0] = 0.0f;
	transformation->m[3][1] = 0.0f;
	transformation->m[3][2] = 0.0f;
	transformation->m[3][3] = 1.0f;
	
	// Do the deletion here
	for (int i = 0; i < 3; ++i)
	{
		delete [] u[i];
		delete [] v[i];
		delete [] ut[i];
		delete [] r[i];
	}
	delete [] u;
	delete [] v;
	delete [] ut;	
	delete [] r;
	delete [] w;
}


// Find the optimal rigid transformation that will
// bring the point clouds into alignment.
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
void optimize_rigid2D(  _reg_blockMatchingParam *params,
                        mat44 * final)
{
    unsigned num_points = params->activeBlockNumber;
    // Keep a sorted list of the distance measure
    std::priority_queue<_reg_sorted_point2D> queue;
    std::vector<_reg_sorted_point2D> top_points;
    double distance = 0.0;
    double lastDistance = 0.0;
    unsigned long i;

    // Set the current transformation to identity
    final->m[0][0] = final->m[1][1] = final->m[2][2] = final->m[3][3] = 1.0f;
    final->m[0][1] = final->m[0][2] = final->m[0][3] = 0.0f;
    final->m[1][0] = final->m[1][2] = final->m[1][3] = 0.0f;
    final->m[2][0] = final->m[2][1] = final->m[2][3] = 0.0f;
    final->m[3][0] = final->m[3][1] = final->m[3][2] = 0.0f;

    for (unsigned j = 0; j < num_points * 2; j+= 2){
        top_points.push_back(_reg_sorted_point2D(&(params->targetPosition[j]),
        &(params->resultPosition[j]), 0.0f));
    }
1457

Marc Modat's avatar