A program (in C) to find the distance to an object using two images and computing distances accross these images (thanks to a stereoscopy algorithm).

stereo.c 46KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345
  1. /*
  2. --------------------------------------------------------------------------------------------------------------------
  3. ------- STEREOSCOPY DISTANCE MEASUREMENT ---------------------------------------------------------------------------
  4. --------------------------------------------------------------------------------------------------------------------
  5. Please, send me an email if you use or modify this program, just to let me know if this program is useful to anybody or how did you improve it :) You can also send me an email to tell me how lame it is ! :)
  6. TLDR; I don't give a damn to anything you can do using this code. It would just be nice to quote where the original code comes from.
  7. --------------------------------------------------------------------------------
  8. "THE NO-ALCOHOL BEER-WARE LICENSE" (Revision 42):
  9. Phyks (webmaster@phyks.me) wrote this file. As long as you retain this notice you
  10. can do whatever you want with this stuff (and you can also do whatever you want
  11. with this stuff without retaining it, but that's not cool...). If we meet some
  12. day, and you think this stuff is worth it, you can buy me a beer soda
  13. in return.
  14. Phyks
  15. ---------------------------------------------------------------------------------
  16. --------------------------------------------------------------------------------------------------------------------
  17. This program computes the mean distance between a stereoscopic camera and an object.
  18. We assume both cameras have the same specs (which are the diameter of the camera's field stop and the focal length).
  19. The code is commented but for more details about the algorithm, please refer to the following article :
  20. http://docs.lib.purdue.edu/cgi/viewcontent.cgi?article=1064&context=ecetr
  21. The distance estimation is just an application of the algorithm described in the previous article. To compute the
  22. displacement vector between the two images, we study the distances between subsets of the images. This is just like if
  23. we had a mask that we could place over the left image and then, we could search the best matching part of the right image.
  24. We are in a three dimensional space (RGB) so we just compute the euclidian distances between each corresponding pixels of
  25. the subsets and then, we compute the mean distance between the two subsets.
  26. Another option is to use FFT transform and phase correlation algorithm. More information cn be found here :
  27. http://docs.opencv.org/doc/tutorials/imgproc/histograms/template_matching/template_matching.html and http://en.wikipedia.org/wiki/Phase_correlation
  28. The sobel argument makes the program perform a Sobel edge detection first.
  29. Notes :
  30. - We use the openCV library to easily load and go through the images. OpenCV is a C library for computer vision licensed
  31. under a BSD License (http://opensource.org/licenses/bsd-license.php)
  32. - We use FFTW library to perform FFT. FFTW is a C library to compute FFT licensed under the GNU General Public License (GPL, see http://www.fftw.org/doc/License-and-Copyright.html)
  33. - We compute both X and Y displacements but we'll focus on X displacements to determine the mean distance of the object
  34. as the cameras are supposed to be on the same horizontal plane (Y displacements = vertical displacements are negligible)
  35. - X corresponds to the abscissa and Y to the ordinate of the pixel in the image. They both goes from 0 to ...
  36. Pixels are numeroted this way :
  37. (0,0) (1,0) (2,0) ... (Width,0)
  38. (1,0) (1,1) (2,1) ... (Width,1)
  39. ... ... ... ... ...
  40. (0,Height) ... (Width, Height)
  41. --------------------------------------------------------------------------------------------------------------------
  42. */
  43. #include <stdio.h>
  44. #include <stdlib.h>
  45. #include <assert.h>
  46. #include <opencv2/core/core_c.h>
  47. #include <opencv2/highgui/highgui_c.h>
  48. #include <opencv2/imgproc/imgproc_c.h>
  49. #include <math.h>
  50. #include <getopt.h>
  51. #include <time.h>
  52. #include <pthread.h>
  53. #include <fftw3.h>
  54. #ifndef M_PI
  55. #define M_PI 3.14159265358979323846
  56. #endif
  57. // Structure to store the coordinates of the best matching subsets
  58. struct minXY_struct
  59. {
  60. float min;
  61. int X;
  62. int Y;
  63. };
  64. struct data_find_common
  65. {
  66. const IplImage* img2;
  67. const uchar* p1;
  68. int widthStep1;
  69. int X_1;
  70. int Y_1;
  71. int subset_size;
  72. int X_start;
  73. int Y_start;
  74. int X_end;
  75. int Y_end;
  76. struct minXY_struct* temp;
  77. };
  78. /*
  79. --------------------------------------------------------------------------------------------------------------------
  80. ------- Find common ------------------------------------------------------------------------------------------------
  81. --------------------------------------------------------------------------------------------------------------------
  82. This function takes 10 parameters :
  83. - The image to search in
  84. - The pointer to the pixel in the left-hand corner of the subset we are working on (and its human-readable
  85. coordinates X_1 and Y_1)
  86. - The size of the subsets we consider
  87. - The coordinates of the part of the image to search in
  88. This function will search the best matching subset in the right image to the current subset in the left image.
  89. It will go through the image img2 (aka the right image) and for each pixel, will compute the mean RGB distance between :
  90. - The subset we are working on in the left image
  91. - A subset of the same size in img2 with the current pixel as the left-hand corner
  92. As the images have been opened in color mode, we are working in a three dimensional space (RGB) and we just compute the
  93. euclidian distance pixel to pixel using the colors as components. Then, we compute the mean of this distance over the subset.
  94. This function returns a structure with the X and Y coordinates of the left-hand corner of the best matching subset.
  95. --------------------------------------------------------------------------------------------------------------------
  96. */
  97. static void *find_common(void *data)
  98. {
  99. struct data_find_common *data_args = data;
  100. //Variables to explore the right image
  101. uchar *p2, *line2;
  102. //And the subsets
  103. int i = 0, j = 0, k = 0;
  104. //To store the distance between the two subsets (distance) and the distances pixel to pixel (distance_temp)
  105. float distance = 0, distance_temp = 0;
  106. //Human readables coordinates corresponding to p2
  107. int X_temp = data_args->X_start, Y_temp = data_args->Y_start;
  108. //The structure it will return. We start with a maximal distance in the left-hand corner of the image
  109. struct minXY_struct minXY={255, 0, 0};
  110. //We explore the image line by line from left to right
  111. //Note : we only explore an area with a height equal to the quarter of th total height of the image because the vertical displacement is supposed to be close to 0
  112. for (line2 = (uchar*) data_args->img2->imageData + data_args->Y_start*data_args->img2->widthStep;
  113. line2 <= (uchar*) data_args->img2->imageData + data_args->Y_end*data_args->img2->widthStep;
  114. line2 += data_args->img2->widthStep)
  115. {
  116. for (p2 = line2 + data_args->X_start*data_args->img2->nChannels; p2 <= line2 + data_args->X_end*data_args->img2->nChannels; p2 += data_args->img2->nChannels)
  117. {
  118. distance = 0;
  119. //For each pixels, we calculate the mean distance for the subset_size pixel box around it
  120. for(i = 0; i<data_args->subset_size; i++) //i = iterate through the pixels in a line
  121. {
  122. for(j = 0; j<data_args->subset_size; j++) //j = iterate through the lines
  123. {
  124. distance_temp = 0;
  125. for(k = 0; k < data_args->img2->nChannels; k++) //k = iterate through the channels
  126. {
  127. distance_temp += pow(*(p2 + i*data_args->img2->nChannels + k + j*data_args->img2->widthStep) - *(data_args->p1 + i*data_args->img2->nChannels + k + j*data_args->widthStep1),2); //Works because img1 and img2 have the same number of channels
  128. }
  129. distance += sqrt(distance_temp);
  130. }
  131. }
  132. distance /= pow(data_args->subset_size,2); //Distance is the mean distance over the subset
  133. //And if it is better than the previous min, we store the new coordinates
  134. //We prefer a smaller distance
  135. // But at equal distance, we prefer the closer pixels and the minimal vertical displacement (as it is supposed to be 0 because cameras are on a same horizontal plane)
  136. if(distance < minXY.min || (distance == minXY.min && (sqrt(pow(X_temp-data_args->X_1, 2) + pow(Y_temp-data_args->Y_1, 2)) < sqrt(pow(minXY.X-data_args->X_1, 2) + pow(minXY.Y-data_args->Y_1, 2)) || abs(Y_temp - data_args->Y_1) < abs(minXY.Y - data_args->Y_1))))
  137. {
  138. minXY.X = X_temp;
  139. minXY.Y = Y_temp;
  140. minXY.min = distance;
  141. }
  142. X_temp++;
  143. }
  144. X_temp = data_args->X_start;
  145. Y_temp++;
  146. }
  147. //Store the informations (coordinates and minimum) in a structure
  148. *data_args->temp = minXY;
  149. return NULL;
  150. }
  151. /*
  152. --------------------------------------------------------------------------------------------------------------------
  153. ------- Compute mean distance --------------------------------------------------------------------------------------
  154. --------------------------------------------------------------------------------------------------------------------
  155. This function takes 6 parameters :
  156. - The abscissas of the pixels in the left and in the right image
  157. - The width of the two images
  158. - The distance between the cameras and the angle theta computed previously
  159. We compute the mean distance of the given object by the algorithm described in the article above and return it or
  160. return -1 if there was an error.
  161. --------------------------------------------------------------------------------------------------------------------
  162. */
  163. float compute_mean_distance(int X_1, int X_2, int widthL, int widthR, float theta, float deltaX)
  164. {
  165. float alpha_1, alpha_2;
  166. //If the object is located between two cameras
  167. if(X_1 > widthL / 2 && X_2 < widthR / 2)
  168. {
  169. alpha_1 = atan((X_1 - (widthL / 2))*tan(theta)/(widthL / 2));
  170. alpha_2 = atan(((widthR / 2) - X_2)*tan(theta)/(widthR / 2));
  171. return tan(M_PI/2 - alpha_1)*tan(M_PI/2 - alpha_2)*deltaX / (tan(M_PI/2 - alpha_1) + tan(M_PI/2 - alpha_2));
  172. }
  173. //If the object is on the left side of both cameras
  174. if(X_1 < widthL / 2 && X_2 < widthR / 2)
  175. {
  176. alpha_1 = atan(((widthL / 2) - X_1)*tan(theta)/(widthL / 2));
  177. alpha_2 = atan(((widthR / 2) - X_2)*tan(theta)/(widthR / 2));
  178. return sin(M_PI/2 - alpha_1)*sin(M_PI/2 - alpha_2)*deltaX / sin(alpha_2 - alpha_1);
  179. }
  180. //If the object is on the right side of both cameras
  181. if(X_1 > widthL / 2 && X_2 > widthR / 2)
  182. {
  183. alpha_1 = atan((X_1 - (widthL / 2))*tan(theta)/(widthL / 2));
  184. alpha_2 = atan((X_2 - (widthR / 2))*tan(theta)/(widthR / 2));
  185. return sin(M_PI/2 - alpha_1)*sin(M_PI/2 - alpha_2)*deltaX / sin(alpha_1 - alpha_2);
  186. }
  187. //If the object is exactly in front of the left camera
  188. if(X_1 == widthL / 2)
  189. {
  190. alpha_2 = atan(((widthR / 2) - X_2)*tan(theta)/(widthR / 2));
  191. return tan(M_PI/2 - alpha_2)*deltaX;
  192. }
  193. //If the object is exactly in front of the right camera
  194. if(X_2 == widthR / 2)
  195. {
  196. alpha_1 = atan((X_1 - (widthL / 2))*tan(theta)/(widthL / 2));
  197. return tan(M_PI/2 - alpha_1)*deltaX;
  198. }
  199. return -1;
  200. }
  201. /*
  202. --------------------------------------------------------------------------------------------------------------------
  203. ------- Print help message -----------------------------------------------------------------------------------------
  204. --------------------------------------------------------------------------------------------------------------------
  205. */
  206. void print_help(FILE* stream)
  207. {
  208. fprintf(stream, "\nThis program computes the mean distance between a stereoscopic camera and an object. We assume both cameras have the same specs (which are the diameter of the camera's field stop and the focal length).\n");
  209. fprintf(stream, "\nFor more details about the algorithm, please refer to the following article : http://docs.lib.purdue.edu/cgi/viewcontent.cgi?article=1064&context=ecetr\n");
  210. fprintf(stream, "\nThe distance estimation is just an application of the algorithm described in the previous article. To compute the displacement vector between the two images, we study the distances between subsets of the images. This is just like ifwe had a mask that we could place over the left image and then, we could search the best matching part of the right image.\n");
  211. fprintf(stream, "\nNotes : \n");
  212. fprintf(stream, "- We use the openCV library to easily load and go through the images. OpenCV is a C library for computer vision licensed under a BSD License (http://opensource.org/licenses/bsd-license.php)\n");
  213. fprintf(stream, "- We compute both X and Y displacements but we'll focus on X displacements to determine the mean distance of the object as the cameras are supposed to be on the same horizontal plane (Y displacements = vertical displacements are negligible)\n");
  214. fprintf(stream, "- X corresponds to the abscissa and Y to the ordinate of the pixel in the image. They both goes from 0 to ...\n");
  215. fprintf(stream, "\nPixels are numeroted this way :\n");
  216. fprintf(stream, "(0,0)\t(1,0)\t(2,0)\t...\t(Width,0)\n");
  217. fprintf(stream, "(1,0)\t(1,1)\t(2,1)\t...\t(Width,1)\n");
  218. fprintf(stream, " ...\t ...\t ...\t...\t ...\n");
  219. fprintf(stream, "(0,Height)\t ...\t\t(Width, Height)\n");
  220. fprintf(stream, "\n======================================\n");
  221. fprintf(stream, "\n Usage : \n");
  222. fprintf(stream, "\t -l (--left) \t Path to the left image\n");
  223. fprintf(stream, "\t -r (--right) \t Path to the right image\n");
  224. fprintf(stream, "\t -D (--diameter) (float) Diameter of the camera's field stop\n");
  225. fprintf(stream, "\t -f (--focal) \t (float) Focal length of the camera\n");
  226. fprintf(stream, "\t -d (--delta) \t (float) Distance between the two cameras\n");
  227. fprintf(stream, "\t -s (--size) \t [Optional] (int) Size of the subsets used, default is 50\n");
  228. fprintf(stream, "\t -x (--abscissa) [Optional] (int) Abscissa of the pixel to compute the mean distance\n");
  229. fprintf(stream, "\t -y (--ordinate) [Optional] (int) Ordinate of the pixel to compute the mean distance\n");
  230. fprintf(stream, "\t -c (--choose) \t [Optional] To display the image and select which pixel you want to work with (same as -x and -y but useful if you don't know the coordinates of the pixel)\n");
  231. fprintf(stream, "\t -o (--output) \t [Optional] Path to a file to store the output\n");
  232. fprintf(stream, "\t -S (--sobel) \t [Optional] Run a Sobel edges detection algorithm on both left and right images first to work only on edges. This option won't have any effect if working in single pixel mode.\n");
  233. fprintf(stream, "\t -F (--fft) \t [Optional] Use cross-correlation and fft based method (faster but a little bit less accurate).\n");
  234. fprintf(stream, "\t -H (--hamming) \t [Optional] Use an hamming window to improve FFT (but slightly slower).\n");
  235. fprintf(stream, "\t -h (--help) \t Display this error message\n");
  236. }
  237. /*
  238. --------------------------------------------------------------------------------------------------------------------
  239. ------- Min -----------------------------------------------------------------------------------------
  240. --------------------------------------------------------------------------------------------------------------------
  241. Return the min of a and b
  242. */
  243. int minimum(int a, int b)
  244. {
  245. if(a < b)
  246. return a;
  247. else
  248. return b;
  249. }
  250. /*
  251. --------------------------------------------------------------------------------------------------------------------
  252. ------- Max --------------------------------------------------------------------------------------------------------
  253. --------------------------------------------------------------------------------------------------------------------
  254. Return the max of a and b
  255. */
  256. int maximum(int a, int b)
  257. {
  258. if(a > b)
  259. return a;
  260. else
  261. return b;
  262. }
  263. /*
  264. --------------------------------------------------------------------------------------------------------------------
  265. ------- Mouse Handler ----------------------------------------------------------------------------------------------
  266. --------------------------------------------------------------------------------------------------------------------
  267. Handle the left button click and get the coordinates of the current pixel
  268. */
  269. void mouseHandler(int event, int x, int y, int flags, void* param)
  270. {
  271. if(event == CV_EVENT_LBUTTONDOWN) //If left click
  272. {
  273. int** input = param;
  274. *input[0] = x; //Get the current coordinates
  275. *input[1] = y;
  276. cvDestroyAllWindows(); //And close the window
  277. }
  278. }
  279. /*
  280. --------------------------------------------------------------------------------------------------------------------
  281. ------- Find_FFT ---------------------------------------------------------------------------------------------
  282. --------------------------------------------------------------------------------------------------------------------
  283. Find a template (tpl) in an image (src)
  284. Note : template and src must be the same size
  285. */
  286. struct Peak
  287. {
  288. CvPoint pt;
  289. double maxval;
  290. };
  291. /*
  292. Old version using OpenCV
  293. ---------------------------------
  294. struct Peak Find_FFT(IplImage* src, IplImage* tpl)
  295. {
  296. CvSize imgSize = cvSize(src->width, src->height); //Size of the src image
  297. CvMat tmp;
  298. //src and tpl must be the same size
  299. assert(src->width == tpl->width);
  300. assert(src->height == tpl->height);
  301. // Allocate floating point frames used for DFT (real, imaginary and complex)
  302. IplImage* realInput = cvCreateImage( imgSize, IPL_DEPTH_64F, 1 );
  303. IplImage* imaginaryInput = cvCreateImage( imgSize, IPL_DEPTH_64F, 1 );
  304. IplImage* complexInput = cvCreateImage( imgSize, IPL_DEPTH_64F, 2 );
  305. //Find best size for DFT
  306. int nDFTHeight= cvGetOptimalDFTSize( imgSize.height );
  307. int nDFTWidth= cvGetOptimalDFTSize( imgSize.width );
  308. CvSize dftSize = cvSize(nDFTWidth, nDFTHeight);
  309. //Images that will store DFT
  310. CvMat* src_DFT = cvCreateMat( nDFTHeight, nDFTWidth, CV_64FC2 );
  311. CvMat* tpl_DFT = cvCreateMat( nDFTHeight, nDFTWidth, CV_64FC2 );
  312. //Images used to compute modulus
  313. IplImage* imageRe = cvCreateImage( dftSize, IPL_DEPTH_64F, 1 );
  314. IplImage* imageIm = cvCreateImage( dftSize, IPL_DEPTH_64F, 1 );
  315. IplImage* imageImMag = cvCreateImage( dftSize, IPL_DEPTH_64F, 1 );
  316. IplImage* imageMag = cvCreateImage( dftSize, IPL_DEPTH_64F, 1 );
  317. // Processing of src
  318. cvScale(src,realInput,1.0,0); //Convert it to CV_32F (float)
  319. cvZero(imaginaryInput);
  320. cvMerge(realInput,imaginaryInput,NULL,NULL,complexInput);
  321. cvGetSubRect(src_DFT,&tmp,cvRect(0,0,src->width,src->height));
  322. cvCopy(complexInput,&tmp,NULL);
  323. if (src_DFT->cols>src->width)
  324. {
  325. cvGetSubRect(src_DFT,&tmp,cvRect(src->width,0,src_DFT->cols-src->width,src->height));
  326. cvZero(&tmp);
  327. }
  328. cvDFT(src_DFT,src_DFT,CV_DXT_FORWARD,complexInput->height); //Process DFT
  329. // Processing of tpl
  330. cvScale(tpl,realInput,1.0,0);
  331. cvMerge(realInput,imaginaryInput,NULL,NULL,complexInput);
  332. cvGetSubRect(tpl_DFT,&tmp,cvRect(0,0,tpl->width,tpl->height));
  333. cvCopy(complexInput,&tmp,NULL);
  334. if (tpl_DFT->cols>tpl->width)
  335. {
  336. cvGetSubRect(tpl_DFT,&tmp,cvRect(tpl->width,0,tpl_DFT->cols-tpl->width,tpl->height));
  337. cvZero( &tmp );
  338. }
  339. cvDFT(tpl_DFT,tpl_DFT,CV_DXT_FORWARD,complexInput->height);
  340. // Multiply spectrums of the scene and the model (use CV_DXT_MUL_CONJ to get correlation instead of convolution)
  341. cvMulSpectrums(src_DFT,tpl_DFT,src_DFT,CV_DXT_MUL_CONJ);
  342. // Split Fourier in real and imaginary parts
  343. cvSplit(src_DFT,imageRe,imageIm,0,0);
  344. // Compute the magnitude of the spectrum components: Mag = sqrt(Re^2 + Im^2)
  345. cvPow( imageRe, imageMag, 2.0 );
  346. cvPow( imageIm, imageImMag, 2.0 );
  347. cvAdd( imageMag, imageImMag, imageMag, NULL );
  348. cvPow( imageMag, imageMag, 0.5 );
  349. // Normalize correlation (Divide real and imaginary components by magnitude)
  350. cvDiv(imageRe,imageMag,imageRe,1.0);
  351. cvDiv(imageIm,imageMag,imageIm,1.0);
  352. cvMerge(imageRe,imageIm,NULL,NULL,src_DFT);
  353. //Inverse dft
  354. cvDFT( src_DFT, src_DFT, CV_DXT_INVERSE_SCALE, complexInput->height );
  355. cvSplit( src_DFT, imageRe, imageIm, 0, 0 );
  356. //Find the peak (greatest magnitude)
  357. double minval = 0.0;
  358. double maxval = 0.0;
  359. CvPoint minloc;
  360. CvPoint maxloc;
  361. cvMinMaxLoc(imageRe,&minval,&maxval,&minloc,&maxloc,NULL);
  362. int x=maxloc.x; // log range
  363. //if (x>(imageRe->width/2))
  364. // x = x-imageRe->width; // positive or negative values
  365. int y=maxloc.y; // angle
  366. //if (y>(imageRe->height/2))
  367. // y = y-imageRe->height; // positive or negative values
  368. struct Peak pk;
  369. pk.maxval= maxval;
  370. pk.pt=cvPoint(x,y);
  371. cvReleaseImage(&realInput);
  372. cvReleaseImage(&imaginaryInput);
  373. cvReleaseImage(&complexInput);
  374. cvReleaseImage(&imageRe);
  375. cvReleaseImage(&imageIm);
  376. cvReleaseImage(&imageImMag);
  377. cvReleaseImage(&imageMag);
  378. cvReleaseMat(&src_DFT);
  379. cvReleaseMat(&tpl_DFT);
  380. return pk;
  381. }
  382. -----------------------------------------*/
  383. /* New version, using FFTW (multithreaded)
  384. ------------------------------------------
  385. */
  386. struct Peak Find_FFT(IplImage* src, IplImage* tpl, int hamming)
  387. {
  388. int i, j, k = 0;
  389. double tmp; //To store the modulus temporarily
  390. //src and tpl must be the same size
  391. assert(src->width == tpl->width);
  392. assert(src->height == tpl->height);
  393. // Get image properties
  394. int width = src->width;
  395. int height = src->height;
  396. int step = src->widthStep;
  397. int fft_size = width * height;
  398. fftw_init_threads(); //Initialize FFTW for multithreading with a max number of 2 threads (more is not efficient)
  399. fftw_plan_with_nthreads(2);
  400. //Allocate arrays for FFT of src and tpl
  401. fftw_complex *src_spatial = ( fftw_complex* )fftw_malloc( sizeof( fftw_complex ) * width * height );
  402. fftw_complex *src_freq = ( fftw_complex* )fftw_malloc( sizeof( fftw_complex ) * width * height );
  403. fftw_complex *tpl_spatial = ( fftw_complex* )fftw_malloc( sizeof( fftw_complex ) * width * height );
  404. fftw_complex *tpl_freq = ( fftw_complex* )fftw_malloc( sizeof( fftw_complex ) * width * height );
  405. fftw_complex *res_spatial = ( fftw_complex* )fftw_malloc( sizeof( fftw_complex ) * width * height ); //Result = Cross correlation
  406. fftw_complex *res_freq = ( fftw_complex* )fftw_malloc( sizeof( fftw_complex ) * width * height );
  407. // Setup pointers to images
  408. uchar *src_data = (uchar*) src->imageData;
  409. uchar *tpl_data = (uchar*) tpl->imageData;
  410. // Fill the structure that will be used by fftw
  411. for(i = 0; i < height; i++)
  412. {
  413. for(j = 0 ; j < width ; j++, k++)
  414. {
  415. src_spatial[k][0] = (double) src_data[i * step + j];
  416. src_spatial[k][1] = 0.0;
  417. tpl_spatial[k][0] = (double) tpl_data[i * step + j];
  418. tpl_spatial[k][1] = 0.0;
  419. }
  420. }
  421. // Hamming window to improve FFT (but slightly slower to compute)
  422. if(hamming == 1)
  423. {
  424. double omega = 2.0*M_PI/(fft_size-1);
  425. double A= 0.54;
  426. double B= 0.46;
  427. for(i=0,k=0;i<height;i++)
  428. {
  429. for(j=0;j<width;j++,k++)
  430. {
  431. src_spatial[k][0]= (src_spatial[k][0])*(A-B*cos(omega*k));
  432. tpl_spatial[k][0]= (tpl_spatial[k][0])*(A-B*cos(omega*k));
  433. }
  434. }
  435. }
  436. // Setup FFTW plans
  437. fftw_plan plan_src = fftw_plan_dft_2d(height, width, src_spatial, src_freq, FFTW_FORWARD, FFTW_ESTIMATE);
  438. fftw_plan plan_tpl = fftw_plan_dft_2d(height, width, tpl_spatial, tpl_freq, FFTW_FORWARD, FFTW_ESTIMATE);
  439. fftw_plan plan_res = fftw_plan_dft_2d(height, width, res_freq, res_spatial, FFTW_BACKWARD, FFTW_ESTIMATE);
  440. // Execute the FFT of the images
  441. fftw_execute(plan_src);
  442. fftw_execute(plan_tpl);
  443. // Compute the cross-correlation
  444. for(i = 0; i < fft_size ; i++ )
  445. {
  446. res_freq[i][0] = tpl_freq[i][0] * src_freq[i][0] + tpl_freq[i][1] * src_freq[i][1];
  447. res_freq[i][1] = tpl_freq[i][0] * src_freq[i][1] - tpl_freq[i][1] * src_freq[i][0];
  448. tmp = sqrt(pow(res_freq[i][0], 2.0) + pow(res_freq[i][1], 2.0));
  449. res_freq[i][0] /= tmp;
  450. res_freq[i][1] /= tmp;
  451. }
  452. // Get the phase correlation array = compute inverse fft
  453. fftw_execute(plan_res);
  454. // Find the peak
  455. struct Peak pk;
  456. IplImage* peak_find = cvCreateImage(cvSize(tpl->width,tpl->height ), IPL_DEPTH_64F, 1);
  457. double *peak_find_data = (double*) peak_find->imageData;
  458. for( i = 0 ; i < fft_size ; i++ )
  459. {
  460. peak_find_data[i] = res_spatial[i][0] / (double) fft_size;
  461. }
  462. CvPoint minloc, maxloc;
  463. double minval, maxval;
  464. cvMinMaxLoc(peak_find, &minval, &maxval, &minloc, &maxloc, 0);
  465. pk.pt = maxloc;
  466. pk.maxval = maxval;
  467. // Clear memory
  468. fftw_destroy_plan(plan_src);
  469. fftw_destroy_plan(plan_tpl);
  470. fftw_destroy_plan(plan_res);
  471. fftw_free(src_spatial);
  472. fftw_free(tpl_spatial);
  473. fftw_free(src_freq);
  474. fftw_free(tpl_freq);
  475. fftw_free(res_spatial);
  476. fftw_free(res_freq);
  477. cvReleaseImage(&peak_find);
  478. fftw_cleanup_threads(); //Cleanup everything else related to FFTW
  479. return pk;
  480. }
  481. /*
  482. --------------------------------------------------------------------------------------------------------------------
  483. ------- Main function ----------------------------------------------------------------------------------------------
  484. --------------------------------------------------------------------------------------------------------------------
  485. */
  486. int main (int argc, char* argv[])
  487. {
  488. //---------------------------
  489. //Initialization of variables
  490. //---------------------------
  491. //To handle the options
  492. const char* const short_options = "hl:r:D:f:d:s:x:y:o:cSFH";
  493. const struct option long_options[] = {
  494. { "help", 0, NULL, 'h' },
  495. { "left", 1, NULL, 'l' },
  496. { "right", 1, NULL, 'r' },
  497. { "diameter", 1, NULL, 'D' },
  498. { "focal", 1, NULL, 'f' },
  499. { "delta", 1, NULL, 'd' },
  500. { "size", 1, NULL, 's' },
  501. { "abscissa", 1, NULL, 'x' },
  502. { "ordinate", 1, NULL, 'y' },
  503. { "output", 1, NULL, 'o' },
  504. { "choose", 0, NULL, 'c' },
  505. { "sobel", 0, NULL, 'S' },
  506. {"fft", 0, NULL, 'F'},
  507. {"hamming", 0, NULL, 'H'},
  508. { NULL, 0, NULL, 0 }
  509. };
  510. int next_option = 0;
  511. //Threads
  512. pthread_t thread1, thread2, thread3, thread4;
  513. struct data_find_common data1, data2, data3, data4;
  514. //To store the images
  515. IplImage* imgL = NULL;
  516. IplImage* imgR = NULL;
  517. uchar *p1, *line1;
  518. //Max X and Y for the images (to avoid computing it many times)
  519. int X_maxL, Y_maxL, X_maxR, Y_maxR;
  520. //Path to images
  521. const char* src_pathL = NULL; //Const ?
  522. const char* src_pathR = NULL;
  523. //Matrices
  524. int array_size = 0; //Size of the matrices we'll create
  525. int **displacements; //To store the displacements for every subset
  526. float *mean_distance;
  527. //To store the parameters
  528. float D = 0, f = 0, deltaX = 0;
  529. int X_input = -1, Y_input = -1, c = 0, sobel = 0, fft = 0, hamming = 0;
  530. int CVLOAD = CV_LOAD_IMAGE_COLOR;
  531. FILE *output_file = stdout; //By default, the output will be stored in stdout
  532. const char* output = NULL;
  533. //The size of the subset, 50 pixels by default.
  534. int subset_size = 50;
  535. //theta = half angle of view of the cameras, alphas cf. article
  536. float theta;
  537. //To iterate and compute the mean distances
  538. int X_1, Y_1, X_2;
  539. int j=0, key, char_temp;
  540. float min;
  541. CvMat tmp, tmp2;
  542. //Temporary structures to store what find_common returns
  543. struct minXY_struct temp1={255, 0, 0};
  544. struct minXY_struct temp2={255, 0, 0};
  545. struct minXY_struct temp3={255, 0, 0};
  546. struct minXY_struct temp4={255, 0, 0};
  547. //Images for sobel
  548. IplImage* imgL_gray = NULL;
  549. IplImage* imgL_Sobelx = NULL;
  550. IplImage* imgL_Sobely = NULL;
  551. IplImage* imgL_Sobel = NULL;
  552. IplImage* imgR_gray = NULL;
  553. IplImage* imgR_Sobelx = NULL;
  554. IplImage* imgR_Sobely = NULL;
  555. IplImage* imgR_Sobel = NULL;
  556. //Image for FFT
  557. IplImage* template = NULL;
  558. //Time
  559. clock_t start=clock();
  560. //----------------------------------------------------------
  561. //Store the options and the parameters in corresponding vars
  562. //----------------------------------------------------------
  563. do {
  564. next_option = getopt_long(argc, argv, short_options, long_options, NULL);
  565. switch(next_option)
  566. {
  567. case 'h':
  568. print_help(stdout);
  569. return EXIT_SUCCESS;
  570. case 'l':
  571. src_pathL = optarg;
  572. break;
  573. case 'r':
  574. src_pathR = optarg;
  575. break;
  576. case 'D':
  577. D = atof(optarg);
  578. break;
  579. case 'f':
  580. f = atof(optarg);
  581. break;
  582. case 'd':
  583. deltaX = atof(optarg);
  584. break;
  585. case 's':
  586. subset_size = atoi(optarg);
  587. break;
  588. case 'x':
  589. X_input = atoi(optarg);
  590. break;
  591. case 'y':
  592. Y_input = atoi(optarg);
  593. break;
  594. case 'o':
  595. output = optarg;
  596. break;
  597. case 'c':
  598. c = 1;
  599. break;
  600. case 'S':
  601. sobel = 1;
  602. break;
  603. case 'F':
  604. fft = 1;
  605. CVLOAD = CV_LOAD_IMAGE_GRAYSCALE;
  606. break;
  607. case 'H':
  608. hamming = 1;
  609. break;
  610. case -1: // End of arguments list
  611. break;
  612. default: // Unexpected behavior
  613. return EXIT_FAILURE;
  614. }
  615. } while(next_option != -1);
  616. //If not enough arguments -> error + help message
  617. if(src_pathL == NULL || src_pathR == NULL || D == 0 || f == 0 || deltaX == 0)
  618. {
  619. fprintf(stderr, "Not enough arguments. You must provide the paths to the two images, the diameter, the focal length and the distance between the two cameras. Please refer to the help message below for more details.\n");
  620. fprintf(stderr, "======================================\n");
  621. fprintf(stderr, "Help :\n");
  622. print_help(stderr);
  623. return EXIT_FAILURE;
  624. }
  625. //If the output must be written in a file, open it
  626. if(output != NULL)
  627. {
  628. output_file = fopen(output, "w");
  629. }
  630. //------------------------------------------------
  631. //Load the images and define the needed parameters
  632. //------------------------------------------------
  633. //We load the images in color mode even if they are greyscale to avoid problems with images with different color modes for the two images
  634. if (!(imgL = cvLoadImage (src_pathL, CVLOAD)))
  635. {
  636. fprintf (stderr, "couldn't open image file: %s\n",src_pathL);
  637. return EXIT_FAILURE;
  638. }
  639. if (!(imgR = cvLoadImage (src_pathR, CVLOAD)))
  640. {
  641. fprintf (stderr, "couldn't open image file: %s\n", src_pathR);
  642. return EXIT_FAILURE;
  643. }
  644. //Check that the images have 3 channels and 8 bits depth (to store values in char)
  645. if(CVLOAD == CV_LOAD_IMAGE_COLOR)
  646. {
  647. assert (imgL->depth == IPL_DEPTH_8U && imgL->nChannels == 3);
  648. assert (imgR->depth == IPL_DEPTH_8U && imgR->nChannels == 3);
  649. }
  650. else
  651. {
  652. assert (imgL->depth == IPL_DEPTH_8U && imgL->nChannels == 1);
  653. assert (imgR->depth == IPL_DEPTH_8U && imgR->nChannels == 1);
  654. }
  655. fprintf(output_file, "Now working with %d*%d subset. \n", subset_size, subset_size);
  656. theta = atan(D/(2*f));
  657. //Last coordinates we can study (due to the size of the subset)
  658. X_maxL = imgL->width - subset_size;
  659. Y_maxL = imgL->imageSize/imgL->widthStep - subset_size;
  660. X_maxR = imgR->width - subset_size;
  661. Y_maxR = imgR->imageSize/imgR->widthStep - subset_size;
  662. //-------------------------------------------------------------------------------------------
  663. //Test that there's something (interesting) to do, ie that subset_size < imgSize / 2 and same for Y
  664. //-------------------------------------------------------------------------------------------
  665. if(floor(imgL->width/2) < subset_size || floor((imgL->imageSize / imgL->widthStep) / 2) < subset_size)
  666. {
  667. fprintf(stderr, "Error : subset is greater than the half of the image. Please choose a smaller subset size.\n");
  668. cvReleaseImage(&imgL);
  669. cvReleaseImage(&imgR);
  670. return EXIT_FAILURE;
  671. }
  672. //---------------------------------------------------------
  673. //Get the coordinates of the pixels if argument "-c" passed
  674. //---------------------------------------------------------
  675. while(c != 0)
  676. {
  677. int *input[2] = {&X_input, &Y_input};
  678. cvNamedWindow("Select the pixel to work with", 1); //Create a window, display the image and add the mouse handler
  679. cvSetMouseCallback("Select the pixel to work with", mouseHandler, (void*) &input);
  680. cvShowImage("Select the pixel to work with", imgL);
  681. cvWaitKey(0);
  682. printf("Now working with the pixel : (%d,%d).\n", X_input, Y_input);
  683. printf("Is it ok ? [y/N] \n");
  684. do
  685. {
  686. key = fgetc(stdin);
  687. while (char_temp != '\n' && char_temp != EOF)
  688. {
  689. char_temp = getchar();
  690. }
  691. }while(key != 89 && key != 121 && key != 110 && key != 78 && key != 10);
  692. if(key == 89 || key == 121 || key == 10)
  693. {
  694. c = 0;
  695. }
  696. }
  697. //-----------------------------------------------
  698. //Applicate an edge detection algorithm if needed
  699. //-----------------------------------------------
  700. if(sobel != 0 && X_input < 0 && Y_input < 0)
  701. {
  702. //First, apply a gaussian blur
  703. cvSmooth(imgL, imgL, CV_GAUSSIAN, 3, 3, 0, 0);
  704. cvSmooth(imgR, imgR, CV_GAUSSIAN, 3, 3, 0, 0);
  705. //Convert images to greyscale
  706. imgL_gray = cvCreateImage(cvGetSize(imgL),imgL->depth,1);
  707. imgL_Sobelx = cvCreateImage(cvGetSize(imgL_gray),imgL_gray->depth,1);
  708. imgL_Sobely = cvCreateImage(cvGetSize(imgL_gray),imgL_gray->depth,1);
  709. imgL_Sobel = cvCreateImage(cvGetSize(imgL_gray),imgL_gray->depth,1);
  710. imgR_gray = cvCreateImage(cvGetSize(imgL),imgL->depth,1);
  711. imgR_Sobelx = cvCreateImage(cvGetSize(imgL_gray),imgL_gray->depth,1);
  712. imgR_Sobely = cvCreateImage(cvGetSize(imgL_gray),imgL_gray->depth,1);
  713. imgR_Sobel = cvCreateImage(cvGetSize(imgL_gray),imgL_gray->depth,1);
  714. cvCvtColor(imgL, imgL_gray, CV_RGB2GRAY);
  715. cvCvtColor(imgR, imgR_gray, CV_RGB2GRAY);
  716. //Gradient X
  717. cvSobel(imgL_gray, imgL_Sobelx, 1, 0, 3);
  718. cvSobel(imgR_gray, imgR_Sobelx, 1, 0, 3);
  719. //Gradient Y
  720. cvSobel(imgL_gray, imgL_Sobely, 0, 1, 3);
  721. cvSobel(imgR_gray, imgR_Sobely, 0, 1, 3);
  722. //Add the two images
  723. cvAdd(imgL_Sobelx, imgL_Sobely, imgL_Sobel, NULL);
  724. cvAdd(imgR_Sobelx, imgR_Sobely, imgR_Sobel, NULL);
  725. //Show the images
  726. printf("The images after edge detection will be shown in a new window.\n");
  727. printf("Press ENTER to continue");
  728. while(getchar() != '\n'){}
  729. cvStartWindowThread();
  730. cvNamedWindow("Edge detection of the left image", CV_WINDOW_AUTOSIZE );
  731. cvShowImage("Edge detection of the left image", imgL_Sobel);
  732. cvWaitKey(0);
  733. cvDestroyWindow("Edge detection of the left image");
  734. cvNamedWindow("Edge detection of the right image", CV_WINDOW_AUTOSIZE );
  735. cvShowImage("Edge detection of the right image", imgR_Sobel);
  736. cvWaitKey(0);
  737. cvDestroyWindow("Edge detection of the right image");
  738. cvReleaseImage(&imgL_Sobelx);
  739. cvReleaseImage(&imgL_Sobely);
  740. cvReleaseImage(&imgR_Sobelx);
  741. cvReleaseImage(&imgR_Sobely);
  742. assert (imgL_Sobel->depth == IPL_DEPTH_8U && imgL_Sobel->nChannels == 1);
  743. assert (imgR_Sobel->depth == IPL_DEPTH_8U && imgR_Sobel->nChannels == 1);
  744. }
  745. //-------------------------------------------------------------------------------------------
  746. //Definition of 2 vectors X and Y to store the coordinates of the displacement between images
  747. //-------------------------------------------------------------------------------------------
  748. if(X_input >= 0 && Y_input >= 0)
  749. {
  750. if(X_input <= X_maxL && Y_input <= Y_maxL)
  751. {
  752. fprintf(output_file, "Working with the %dx%d pixel\n", X_input, Y_input);
  753. array_size = 1; //If we enter a specific pixel, matrices become float
  754. }
  755. else //If x or y is too large, inform the user
  756. {
  757. fprintf(stderr, "Error : x or y is out of the image. Please note that x and y must be such as x<%d and y <%d\n", X_maxL, Y_maxL);
  758. cvReleaseImage(&imgL);
  759. cvReleaseImage(&imgR);
  760. return EXIT_FAILURE;
  761. }
  762. }
  763. else
  764. {
  765. array_size = floor(imgL->imageSize / imgL->widthStep / subset_size) * floor(imgL->width / subset_size);
  766. }
  767. //Allocate memory for all the matrices (and initialize them)
  768. if((displacements = malloc(sizeof(*displacements) * 2)) == NULL)
  769. {
  770. perror("malloc:");
  771. cvReleaseImage(&imgL);
  772. cvReleaseImage(&imgR);
  773. if(sobel != 0)
  774. {
  775. cvReleaseImage(&imgL_Sobel);
  776. cvReleaseImage(&imgR_Sobel);
  777. }
  778. return EXIT_FAILURE;
  779. }
  780. if((displacements[0] = malloc(sizeof(**displacements) * array_size)) == NULL)
  781. {
  782. perror("malloc:");
  783. cvReleaseImage(&imgL);
  784. cvReleaseImage(&imgR);
  785. if(sobel != 0)
  786. {
  787. cvReleaseImage(&imgL_Sobel);
  788. cvReleaseImage(&imgR_Sobel);
  789. }
  790. return EXIT_FAILURE;
  791. }
  792. if((displacements[1] = malloc(sizeof(**displacements) * array_size)) == NULL)
  793. {
  794. perror("malloc:");
  795. cvReleaseImage(&imgL);
  796. cvReleaseImage(&imgR);
  797. if(sobel != 0)
  798. {
  799. cvReleaseImage(&imgL_Sobel);
  800. cvReleaseImage(&imgR_Sobel);
  801. }
  802. return EXIT_FAILURE;
  803. }
  804. if((mean_distance = malloc(sizeof(*mean_distance) * array_size)) == NULL)
  805. {
  806. perror("malloc:");
  807. cvReleaseImage(&imgL);
  808. cvReleaseImage(&imgR);
  809. free(displacements);
  810. if(sobel != 0)
  811. {
  812. cvReleaseImage(&imgL_Sobel);
  813. cvReleaseImage(&imgR_Sobel);
  814. }
  815. return EXIT_FAILURE;
  816. }
  817. for(j = 0; j < array_size; j++)
  818. {
  819. displacements[0][j] = 0;
  820. displacements[1][j] = 0;
  821. mean_distance[j] = 0;
  822. }
  823. //--------------------------------------------------------------------
  824. //Call find_common to fill the matrices and compute the mean distances
  825. //--------------------------------------------------------------------
  826. fprintf(output_file, "Output is : (X-axis, Y-axis) : (Displacement on X-axis, Displacement on Y-axis) -> Mean Distance\n\n");
  827. //If we work with a specific pixel
  828. if(X_input >= 0 && Y_input >= 0 && X_input <= X_maxL && Y_input <= Y_maxL)
  829. {
  830. //Get the pointer to the pixel
  831. p1 = (uchar*) imgL->imageData + Y_input*imgL->widthStep + X_input*imgL->nChannels;
  832. if(fft == 1) //If using FFT
  833. {
  834. template = cvCreateImage(cvSize(imgR->width, imgR->height), IPL_DEPTH_8U, 1);
  835. cvZero(template);
  836. cvGetSubRect(template,&tmp,cvRect(0,0,subset_size,subset_size));
  837. cvGetSubRect(imgL,&tmp2,cvRect(X_input,Y_input,subset_size,subset_size));
  838. cvCopy(&tmp2,&tmp,NULL);
  839. struct Peak pk = Find_FFT(imgR, template, hamming);
  840. X_2 = pk.pt.x;
  841. displacements[0][0] = pk.pt.x - X_input; //(= DeltaX)
  842. displacements[1][0] = pk.pt.y - Y_input; //(=DeltaY)
  843. cvReleaseImage(&template);
  844. }
  845. else
  846. {
  847. //Compute the displacement
  848. // 1 2
  849. // 3 4
  850. //4 threads
  851. data1.img2 = imgR;
  852. data1.p1 = p1;
  853. data1.widthStep1 = imgL->widthStep;
  854. data1.X_1 = X_input;
  855. data1.Y_1 = Y_input;
  856. data1.subset_size = subset_size;
  857. data1.X_start = 0;
  858. data1.Y_start = maximum(0, Y_input - (int) floor(imgR->imageSize/8/imgR->widthStep));
  859. data1.X_end = floor(X_maxR/2);
  860. data1.Y_end = Y_input;
  861. data1.temp = &temp1;
  862. pthread_create (&thread1, NULL, find_common, &data1);
  863. data2.img2 = imgR;
  864. data2.p1 = p1;
  865. data2.widthStep1 = imgL->widthStep;
  866. data2.X_1 = X_input;
  867. data2.Y_1 = Y_input;
  868. data2.subset_size = subset_size;
  869. data2.X_start = (int) floor(X_maxR/2) + 1;
  870. data2.Y_start = maximum(0, Y_input - (int) floor(imgR->imageSize/8/imgR->widthStep));
  871. data2.X_end = X_maxR;
  872. data2.Y_end = Y_input;
  873. data2.temp = &temp2;
  874. pthread_create (&thread2, NULL, find_common, &data2);
  875. data3.img2 = imgR;
  876. data3.p1 = p1;
  877. data3.widthStep1 = imgL->widthStep;
  878. data3.X_1 = X_input;
  879. data3.Y_1 = Y_input;
  880. data3.subset_size = subset_size;
  881. data3.X_start = 0;
  882. data3.Y_start = Y_input + 1;
  883. data3.X_end = floor(X_maxR/2);
  884. data3.Y_end = minimum(Y_maxR, Y_input + (int) floor(imgR->imageSize/8/imgR->widthStep));
  885. data3.temp = &temp3;
  886. pthread_create (&thread3, NULL, find_common, &data3);
  887. data4.img2 = imgR;
  888. data4.p1 = p1;
  889. data4.widthStep1 = imgL->widthStep;
  890. data4.X_1 = X_input;
  891. data4.Y_1 = Y_input;
  892. data4.subset_size = subset_size;
  893. data4.X_start = floor(X_maxR/2) + 1;
  894. data4.Y_start = Y_input + 1;
  895. data4.X_end = X_maxR;
  896. data4.Y_end = minimum(Y_maxR, Y_input + (int) floor(imgR->imageSize/8/imgR->widthStep));
  897. data4.temp = &temp4;
  898. pthread_create (&thread4, NULL, find_common, &data4);
  899. //Wait until threads finish
  900. pthread_join(thread1, NULL);
  901. //Compute all the results together
  902. min = temp1.min;
  903. displacements[0][0] = temp1.X - X_input; //(= DeltaX)
  904. displacements[1][0] = temp1.Y - Y_input; //(=DeltaY)
  905. X_2 = temp1.X;
  906. pthread_join(thread2, NULL);
  907. if(temp2.min < min)
  908. {
  909. min = temp2.min;
  910. displacements[0][0] = temp2.X - X_input; //(= DeltaX)
  911. displacements[1][0] = temp2.Y - Y_input; //(=DeltaY)
  912. X_2 = temp2.X;
  913. }
  914. pthread_join(thread3, NULL);
  915. if(temp3.min < min)
  916. {
  917. min = temp3.min;
  918. displacements[0][0] = temp3.X - X_input; //(= DeltaX)
  919. displacements[1][0] = temp3.Y - Y_input; //(=DeltaY)
  920. X_2 = temp3.X;
  921. }
  922. pthread_join(thread4, NULL);
  923. if(temp4.min < min)
  924. {
  925. min = temp4.min;
  926. displacements[0][0] = temp4.X - X_input; //(= DeltaX)
  927. displacements[1][0] = temp4.Y - Y_input; //(=DeltaY)
  928. X_2 = temp4.X;
  929. }
  930. }
  931. //Compute mean distance
  932. mean_distance[0] = compute_mean_distance(X_input, X_2, imgL->width, imgR->width, theta, deltaX);
  933. if(mean_distance[0] < 0) //If there's an error (mean_distance < 0 is absurd)
  934. {
  935. fprintf(stderr, "An error occurred, negative mean_distance found. Dump :\nCoordinates = (%d, %d) ; Displacement = (%d, %d); Computed value of mean distance : %f\n", X_input, Y_input, displacements[0][0], displacements[1][0], mean_distance[0]);
  936. cvReleaseImage(&imgL);
  937. cvReleaseImage(&imgR);
  938. free(displacements);
  939. free(mean_distance);
  940. if(output != NULL)
  941. fclose(output_file);
  942. return EXIT_FAILURE;
  943. }
  944. else //Else, print the result
  945. {
  946. fprintf(output_file, "(%d, %d) : (%d, %d) -> %f\n", X_input, Y_input, displacements[0][0], displacements[1][0], mean_distance[0]);
  947. }
  948. }
  949. //If we work with the entire image
  950. else
  951. {
  952. j = 0; //We use j to go through the matrices
  953. //Explore the image line by line
  954. for (line1 = (uchar*) imgL->imageData;
  955. line1 <= (uchar*) imgL->imageData + Y_maxL*imgL->widthStep;
  956. line1 += imgL->widthStep*subset_size)
  957. {
  958. for (p1 = line1; p1 <= line1 + X_maxL*imgL->nChannels; p1 += imgL->nChannels*subset_size)
  959. {
  960. //Get the coordinates corresponding to p1
  961. //(p1 = imageData + X_1 + iChannel + Y_1*widthStep) where iChannel is in {0,1,..nChannels}
  962. X_1 = floor(((p1 - (uchar*) imgL->imageData) % imgL->widthStep) / imgL->nChannels);
  963. Y_1 = floor((p1 - (uchar*) imgL->imageData ) / imgL->widthStep);
  964. if(fft == 1) //If using FFT
  965. {
  966. template = cvCreateImage(cvSize(imgR->width, imgR->height), IPL_DEPTH_8U, 1);
  967. cvZero(template);
  968. cvGetSubRect(template,&tmp,cvRect(0,0,subset_size,subset_size));
  969. cvGetSubRect(imgL,&tmp2,cvRect(X_1,Y_1,subset_size,subset_size));
  970. cvCopy(&tmp2,&tmp,NULL);
  971. struct Peak pk = Find_FFT(imgR, template, hamming);
  972. X_2 = pk.pt.x;
  973. displacements[0][0] = pk.pt.x - X_1; //(= DeltaX)
  974. displacements[1][0] = pk.pt.y - Y_1; //(=DeltaY)
  975. cvReleaseImage(&template);
  976. }
  977. else
  978. {
  979. //Compute the displacement
  980. // 1 2
  981. // 3 4
  982. //4 threads
  983. data1.img2 = imgR;
  984. data1.p1 = p1;
  985. data1.widthStep1 = imgL->widthStep;
  986. data1.X_1 = X_1;
  987. data1.Y_1 = Y_1;
  988. data1.subset_size = subset_size;
  989. data1.X_start = 0;
  990. data1.Y_start = maximum(0, Y_1 - (int) floor(imgR->imageSize/8/imgR->widthStep));
  991. data1.X_end = floor(X_maxR/2);
  992. data1.Y_end = Y_1;
  993. data1.temp = &temp1;
  994. pthread_create (&thread1, NULL, find_common, &data1);
  995. data2.img2 = imgR;
  996. data2.p1 = p1;
  997. data2.widthStep1 = imgL->widthStep;
  998. data2.X_1 = X_1;
  999. data2.Y_1 = Y_1;
  1000. data2.subset_size = subset_size;
  1001. data2.X_start = (int) floor(X_maxR/2) + 1;
  1002. data2.Y_start = maximum(0, Y_1 - (int) floor(imgR->imageSize/8/imgR->widthStep));
  1003. data2.X_end = X_maxR;
  1004. data2.Y_end = Y_1;
  1005. data2.temp = &temp2;
  1006. pthread_create (&thread2, NULL, find_common, &data2);
  1007. data3.img2 = imgR;
  1008. data3.p1 = p1;
  1009. data3.widthStep1 = imgL->widthStep;
  1010. data3.X_1 = X_1;
  1011. data3.Y_1 = Y_1;
  1012. data3.subset_size = subset_size;
  1013. data3.X_start = 0;
  1014. data3.Y_start = Y_1 + 1;
  1015. data3.X_end = floor(X_maxR/2);
  1016. data3.Y_end = minimum(Y_maxR, Y_1 + (int) floor(imgR->imageSize/8/imgR->widthStep));
  1017. data3.temp = &temp3;
  1018. pthread_create (&thread3, NULL, find_common, &data3);
  1019. data4.img2 = imgR;
  1020. data4.p1 = p1;
  1021. data4.widthStep1 = imgL->widthStep;
  1022. data4.X_1 = X_1;
  1023. data4.Y_1 = Y_1;
  1024. data4.subset_size = subset_size;
  1025. data4.X_start = floor(X_maxR/2) + 1;
  1026. data4.Y_start = Y_1 + 1;
  1027. data4.X_end = X_maxR;
  1028. data4.Y_end = minimum(Y_maxR, Y_1 + (int) floor(imgR->imageSize/8/imgR->widthStep));
  1029. data4.temp = &temp4;
  1030. pthread_create (&thread4, NULL, find_common, &data4);
  1031. //Wait until threads finish
  1032. pthread_join(thread1, NULL);
  1033. //Compute all the results together
  1034. min = temp1.min;
  1035. displacements[0][j] = temp1.X - X_1; //(= DeltaX)
  1036. displacements[1][j] = temp1.Y - Y_1; //(=DeltaY)
  1037. X_2 = temp1.X;
  1038. pthread_join(thread2, NULL);
  1039. if(temp2.min < min)
  1040. {
  1041. min = temp2.min;
  1042. displacements[0][j] = temp2.X - X_1; //(= DeltaX)
  1043. displacements[1][j] = temp2.Y - Y_1; //(=DeltaY)
  1044. X_2 = temp2.X;
  1045. }
  1046. pthread_join(thread3, NULL);
  1047. if(temp3.min < min)
  1048. {
  1049. min = temp3.min;
  1050. displacements[0][j] = temp3.X - X_1; //(= DeltaX)
  1051. displacements[1][j] = temp3.Y - Y_1; //(=DeltaY)
  1052. X_2 = temp3.X;
  1053. }
  1054. pthread_join(thread4, NULL);
  1055. if(temp4.min < min)
  1056. {
  1057. min = temp4.min;
  1058. displacements[0][j] = temp4.X - X_1; //(= DeltaX)
  1059. displacements[1][j] = temp4.Y - Y_1; //(=DeltaY)
  1060. X_2 = temp4.X;
  1061. }
  1062. }
  1063. //Compute mean distance
  1064. mean_distance[j] = compute_mean_distance(X_1, X_2, imgL->width, imgR->width, theta, deltaX);
  1065. if(mean_distance[j] < 0) //If there's an error (mean_distance < 0 is absurd)
  1066. {
  1067. fprintf(stderr, "An error occurred, negative mean_distance found. Dump :\nCoordinates = (%d, %d) ; Displacement = (%d, %d); Computed value of mean distance : %f\n", X_1, Y_1, displacements[0][j], displacements[1][j], mean_distance[j]);
  1068. fprintf(output_file, "Error, absurd mean distance : (%d, %d) : (%d, %d) -> %f\n", X_1, Y_1, displacements[0][j], displacements[1][j], mean_distance[j]);
  1069. }
  1070. else //Else, print the result
  1071. {
  1072. fprintf(output_file, "(%d, %d) : (%d, %d) -> %f\n", X_1, Y_1, displacements[0][j], displacements[1][j], mean_distance[j]);
  1073. }
  1074. j++;
  1075. }
  1076. }
  1077. }
  1078. //-----------
  1079. //Free memory
  1080. //-----------
  1081. if(sobel != 0)
  1082. {
  1083. cvReleaseImage(&imgL_Sobel);
  1084. cvReleaseImage(&imgR_Sobel);
  1085. }
  1086. cvReleaseImage(&imgL);
  1087. cvReleaseImage(&imgR);
  1088. free(displacements);
  1089. free(mean_distance);
  1090. clock_t end=clock();
  1091. fprintf(output_file, "\nCalcul des distances terminé en %d microsecondes.\n", (int) (end - start));
  1092. if(output != NULL)
  1093. {
  1094. fprintf(stdout, "\nCalcul des distances terminé en %d microsecondes.\n", (int) (end - start));
  1095. fclose(output_file);
  1096. }
  1097. return EXIT_SUCCESS; //And exit ;)
  1098. }
  1099. //Almost there
  1100. //Just some comments to make it ...
  1101. //What ? You'll see soon...
  1102. // Yeah ! Here we go ! 1337 lines of code !