image.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /*
  2. Copyright (C) 2006 Pedro Felzenszwalb
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, write to the Free Software
  13. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  14. */
  15. /* a simple image class */
  16. #ifndef IMAGE_H
  17. #define IMAGE_H
  18. #include <cstring>
  19. template <class T>
  20. class image {
  21. public:
  22. /* create an image */
  23. image(const int width, const int height, const bool init = true);
  24. /* delete an image */
  25. ~image();
  26. /* init an image */
  27. void init(const T &val);
  28. /* copy an image */
  29. image<T> *copy() const;
  30. /* get the width of an image. */
  31. int width() const { return w; }
  32. /* get the height of an image. */
  33. int height() const { return h; }
  34. /* image data. */
  35. T *data;
  36. /* row pointers. */
  37. T **access;
  38. private:
  39. int w, h;
  40. };
  41. /* use imRef to access image data. */
  42. #define imRef(im, x, y) (im->access[y][x])
  43. /* use imPtr to get pointer to image data. */
  44. #define imPtr(im, x, y) &(im->access[y][x])
  45. template <class T>
  46. image<T>::image(const int width, const int height, const bool init) {
  47. w = width;
  48. h = height;
  49. data = new T[w * h]; // allocate space for image data
  50. access = new T*[h]; // allocate space for row pointers
  51. // initialize row pointers
  52. for (int i = 0; i < h; i++)
  53. access[i] = data + (i * w);
  54. if (init)
  55. memset(data, 0, w * h * sizeof(T));
  56. }
  57. template <class T>
  58. image<T>::~image() {
  59. delete [] data;
  60. delete [] access;
  61. }
  62. template <class T>
  63. void image<T>::init(const T &val) {
  64. T *ptr = imPtr(this, 0, 0);
  65. T *end = imPtr(this, w-1, h-1);
  66. while (ptr <= end)
  67. *ptr++ = val;
  68. }
  69. template <class T>
  70. image<T> *image<T>::copy() const {
  71. image<T> *im = new image<T>(w, h, false);
  72. memcpy(im->data, data, w * h * sizeof(T));
  73. return im;
  74. }
  75. #endif