imread_big.m 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. %Tristan Ursell
  2. %Read large image stack (TIFF)
  3. %May 2019
  4. %
  5. % This function can load image stacks larger than 4GB which is the typical
  6. % limitation on image files. Designed to work with single-channel
  7. % uncompressed TIFF stacks. Also works for files smaller than 4GB.
  8. %
  9. % [stack_out,Nframes]= imread_big(stack_name);
  10. % [stack_out,Nframes]= imread_big(stack_name,[i j]);
  11. %
  12. % stack_name = the path and file name to the image stack
  13. %
  14. % [i j] = optional frame number range to load (i = j is allowed)
  15. %
  16. % Nframes = number of frames as determined by total file size divided by
  17. % estimated size of each frame data block
  18. %
  19. % stack_out = the output image stack of size [M N Nframes], where M x N is
  20. % the size of each image.
  21. %
  22. function [stack_out,Nframes] = imread_big(stack_name,varargin)
  23. %get data block size
  24. info1 = imfinfo(stack_name);
  25. stripOffset = info1(1).StripOffsets;
  26. stripByteCounts = info1(1).StripByteCounts;
  27. %get image size
  28. sz_x=info1(1).Width;
  29. sz_y=info1(1).Height;
  30. if length(info1)<2
  31. Nframes=floor(info1(1).FileSize/stripByteCounts);
  32. else
  33. Nframes=length(info1);
  34. end
  35. %read in arguments
  36. if nargin>1
  37. temp1=varargin{1};
  38. ilow=temp1(1);
  39. ihigh=temp1(2);
  40. else
  41. ilow=1;
  42. ihigh=Nframes;
  43. end
  44. %load file id tag
  45. fID = fopen (stack_name, 'r');
  46. if info1(1).BitDepth==32
  47. stack_out = zeros([sz_y sz_x ihigh-ilow+1],'uint32');
  48. elseif info1(1).BitDepth==16
  49. stack_out = zeros([sz_y sz_x ihigh-ilow+1],'uint16');
  50. else
  51. stack_out = zeros([sz_y sz_x ihigh-ilow+1],'uint8');
  52. end
  53. start_point = stripOffset + (0:1:(Nframes-1)).*stripByteCounts;
  54. % start_point = stripOffset(1) + (0:1:(Nframes-1))*stripByteCounts + 1;
  55. q=0;
  56. for i = ilow:ihigh
  57. %fprintf ('loading image ... %d\n', i);
  58. fseek (fID, start_point(i), 'bof');
  59. if info1(1).BitDepth==32
  60. A = fread(fID, [sz_x sz_y], 'uint32=>uint32');
  61. elseif info1(1).BitDepth==16
  62. A = fread(fID, [sz_x sz_y], 'uint16=>uint16');
  63. else
  64. A = fread(fID, [sz_x sz_y], 'uint8=>uint8');
  65. end
  66. q=q+1;
  67. try
  68. stack_out(:,:,q) = A';
  69. catch
  70. disp(['Terminated at frame ' num2str(i) '.'])
  71. break
  72. end
  73. end
  74. %stack_out=stack_out(:,:,1:q);
  75. Nframes=q;
  76. fclose(fID);
  77. end