FindFly.m 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. function [x, y, bodyline, sqr] = FindFly(chunk, sqrsize)
  2. %FINDFLY
  3. %
  4. % Usage:
  5. % [x, y, bodyline, sqr] = FindFly(chunk, sqrsize)
  6. %
  7. % This function takes in a single image matrix (chunk) and finds the fly.
  8. % First, it finds the brightest pixel in the image, then grabs a square
  9. % of size 2*sqrsize pixels around the fly. The center of mass of this
  10. % square is calculated (mass = pixel level) and that is returned as the
  11. % fly position. The variable 'sqr' can be returned, which contains the
  12. % limits defining a bounding box around the fly.
  13. %
  14. % This function also returns the body axis orientation vector. The
  15. % body axis is calcuated using FlyOrient. Fly Orient returns the bodyline
  16. % vector, which is a 2-element vector containing two angles, one in the upper
  17. % half plane, and one in the lower half plane. These angles (which are
  18. % complementary) define the body axis. The noise threshold required for
  19. % FlyOrient is currently fixed at 0.2. If you wish to change this
  20. % threshold, you must go into the FindFly.m file and hard-code a
  21. % different value.
  22. % Written by Dan Valente
  23. % 28 September 2006
  24. noise_thresh = 0.2; % for the FlyOrient function
  25. brightest_pixel_level = max(max(chunk));
  26. [brightpix_row brightpix_col] = find(chunk >= (brightest_pixel_level));
  27. %just in case more spots have the same brightness, only take one...
  28. width = length(chunk(1,:));
  29. height = length(chunk(:,1));
  30. row_pos = brightpix_row(1);
  31. col_pos = brightpix_col(1);
  32. y = row_pos;
  33. x = col_pos;
  34. %take subset of pixels around fly. need to take enough to ensure
  35. %entire fly is captured.
  36. row_lower_limit = row_pos-sqrsize;
  37. row_upper_limit = row_pos+sqrsize;
  38. if (row_lower_limit <= 0)
  39. row_lower_limit = 1;
  40. end
  41. if (row_upper_limit >= height )
  42. row_upper_limit = height;
  43. end
  44. col_lower_limit = col_pos-sqrsize;
  45. col_upper_limit = col_pos+sqrsize;
  46. if (col_lower_limit <= 0)
  47. col_lower_limit = 1;
  48. end
  49. if (col_upper_limit >= width )
  50. col_upper_limit = width;
  51. end
  52. sqr = [row_lower_limit row_upper_limit col_lower_limit col_upper_limit];
  53. %Now grab center of mass of fly (i.e. CM of subset image pixel intensities)
  54. temp_mat = chunk(row_lower_limit:row_upper_limit,col_lower_limit:col_upper_limit);
  55. x2 = [1:length(temp_mat(1,:))]';
  56. y2 = [1:length(temp_mat(:,1))]';
  57. total = sum(sum(temp_mat));
  58. x = sum(temp_mat*x2)/total+col_lower_limit-1;
  59. y = sum(temp_mat'*y2)/total+row_lower_limit-1;
  60. % Find Fly orientation from this frame (in radians)
  61. bodyline = FlyOrient(temp_mat, noise_thresh);
  62. return;