rconv2.m 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. % RES = RCONV2(MTX1, MTX2, CTR)
  2. %
  3. % Convolution of two matrices, with boundaries handled via reflection
  4. % about the edge pixels. Result will be of size of LARGER matrix.
  5. %
  6. % The origin of the smaller matrix is assumed to be its center.
  7. % For even dimensions, the origin is determined by the CTR (optional)
  8. % argument:
  9. % CTR origin
  10. % 0 DIM/2 (default)
  11. % 1 (DIM/2)+1
  12. % Eero Simoncelli, 6/96.
  13. function c = rconv2(a,b,ctr)
  14. if (exist('ctr') ~= 1)
  15. ctr = 0;
  16. end
  17. if (( size(a,1) >= size(b,1) ) & ( size(a,2) >= size(b,2) ))
  18. large = a; small = b;
  19. elseif (( size(a,1) <= size(b,1) ) & ( size(a,2) <= size(b,2) ))
  20. large = b; small = a;
  21. else
  22. error('one arg must be larger than the other in both dimensions!');
  23. end
  24. ly = size(large,1);
  25. lx = size(large,2);
  26. sy = size(small,1);
  27. sx = size(small,2);
  28. %% These values are one less than the index of the small mtx that falls on
  29. %% the border pixel of the large matrix when computing the first
  30. %% convolution response sample:
  31. sy2 = floor((sy+ctr-1)/2);
  32. sx2 = floor((sx+ctr-1)/2);
  33. % pad with reflected copies
  34. clarge = [
  35. large(sy-sy2:-1:2,sx-sx2:-1:2), large(sy-sy2:-1:2,:), ...
  36. large(sy-sy2:-1:2,lx-1:-1:lx-sx2); ...
  37. large(:,sx-sx2:-1:2), large, large(:,lx-1:-1:lx-sx2); ...
  38. large(ly-1:-1:ly-sy2,sx-sx2:-1:2), ...
  39. large(ly-1:-1:ly-sy2,:), ...
  40. large(ly-1:-1:ly-sy2,lx-1:-1:lx-sx2) ];
  41. c = conv2(clarge,small,'valid');