2016-11-18 2 views
0

Я пишу код на C++, который обрабатывает данные изображения ppm. Я создал класс Color, представляющий триплет красных, зеленых, синих значений и класс Image, представляющий общий контейнер данных для изображения. В моем классе Image я хотел бы иметь метод, который получает цвет изображения в месте (x, y).Как получить цвет изображения ppm в месте (x, y)?

My Color класс:

#ifndef _COLOR 
#define _COLOR 


namespace imaging 
{ 
/*! An alias for the floating point representation of color components (32bit per color channel). 
* 
* Each color channel goes from 0.0f (darkness) to 1.0f (full color brightness). 
* For example, bright red is (1,0,0), white is (1,1,1), magenta is (1,0,1) etc. 
*/ 
typedef float component_t; 

/*! Represents a triplet of Red, Green, Blue (RGB) values. 
*/ 
class Color 
{ 
public: 
    // members 
    component_t r, //! The red color channel (component) 
       g, //! The green color channel (component) 
       b; //! The blue color channel (component) 

    // member functions 

    /*! This operator returns the index-th component of the image. 
    * 
    * For speed, no bounds for index values are checked. 
    * 
    * \param index is the index of the component to obtain. Values should be 0, 1 or 2. 
    * 
    * \return a reference to the respective color component. 
    */ 
    component_t & operator [] (size_t index) 
    { 
     return *(&r + index); 
    } 

    /*! Addition operator. 
    * 
    * Adds a color to the current one and returns the result. 
    * 
    * \param right is the right Color operand of the + sign. 
    * 
    * \return the resulting color after the component-wise addition of the two colors. 
    */ 
    Color operator + (Color & right) 
    { 
     Color left; 
     left.r = r + right.r; 
     left.g = g + right.g; 
     left.b = b + right.b; 
     return left; 
    } 

    // constructors 

    /*! Parameterized constructor. 
    * 
    * \param r is the red component of the color. 
    * \param g is the green component of the color. 
    * \param b is the blue component of the color. 
    */ 
    Color(component_t r, component_t g, component_t b) : r(r), g(g), b(b) {} 

    /*! Default constructor. 
    * 
    * All components set to zero, i.e. a black color. 
    */ 
    Color() : r(0), g(0), b(0) {} 
}; 
} 

#endif _COLOR 

Некоторые из моего класса Image является:

/*! The imaging namespace contains every class or function associated with the image storage, compression and manipulation. 
    */ 
     namespace imaging 
    { 

//------------------------------------ class Image ------------------------------------------------ 

/*! It is the class that represents a generic data container for an image. 
* 
* It holds the actual buffer of the pixel values and provides methods for accessing them, 
* either as individual pixels or as a memory block. The Image class alone does not provide 
* any functionality for loading and storing an image, as it is the result or input to such a procedure. 
* 
* The internal buffer of an image object stores the actual bytes (data) of the color image as 
* a contiguous sequence of RGB triplets. Hence, the size of the buffer variable holding these data is 
* 3 X width X height X sizeof(component_t) bytes. 
* 
* All values stored in the internal memory buffer are floating point values and for typical (normalized) 
* intensity ranges, each color component is within the range [0.0, 1.0]. 
*/ 
class Image 
{ 
public: 
    enum channel_t { RED = 0, GREEN, BLUE };   //! You can use the names RED, GREEN, BLUE instead of 0,1,2 to access individual Color channels. 

protected: 
    component_t * buffer;      //! Holds the image data. 

    unsigned int width,       //! The width of the image (in pixels) 
     height;      //! The height of the image (in pixels) 

public: 
    // metric accessors 

    /*! Returns the width of the image 
    */ 
    const unsigned int getWidth() const { return width; } 

    /*! Returns the height of the image 
    */ 
    const unsigned int getHeight() const { return height; } 

    // data accessors 

    /*! Obtains a pointer to the internal data. 
    * 
    * This is NOT a copy of the internal image data, but rather a pointer 
    * to the internally allocated space, so DO NOT attempt to delete the pointer. 
    */ 
    component_t * getRawDataPtr() { 
     return buffer; 
    } 

    /*! Obtains the color of the image at location (x,y). 
    * 
    * The method should do any necessary bounds checking. 
    * 
    * \param x is the (zero-based) horizontal index of the pixel to get. 
    * \param y is the (zero-based) vertical index of the pixel to get. 
    * 
    * \return The color of the (x,y) pixel as a Color object. Returns a black (0,0,0) color in case of an out-of-bounds x,y pair. 
    */ 
    Color getPixel(unsigned int x, unsigned int y) const { 

    } 

Любая помощь приветствуется.

+0

'component_t * buffer;' содержит компонент цвета, а не цвет. Здесь будет отличное место для использования вашего класса «Цвет». – user4581301

+0

Но как я могу определить местоположение x y пикселя? –

+0

Типичная функция отображения от 2D до 1D - это строка 'row * number_columns + column'. В вашем случае это будет 'y * width + x' или' x * height + y' в зависимости от ориентации хранилища. – user4581301

ответ

0
component_t * buffer; 

требует, чтобы собрать три отдельных component_t сек в Color для возвращения на Color getPixel(unsigned int x, unsigned int y). Отключение одной или другой математической ошибкой, и вы упакуете неправильные компоненты в Color и возвращаете плохие данные. Однако это делает запись component_t * getRawDataPtr() мертвой легкостью.

Для построения Color из buffer шаг за шагом вам необходимо:

  1. Вычислительный расположение пикселей: pixeloffset = у * ширина + х
  2. Есть три компонента на пиксель, так что: componentoffset = pixeloffset * 3
  3. Таким образом, первый компонент пикселя на: пиксель = буфер + componentoffset
  4. Теперь, когда вы знаете, где пиксель, вы подаете пикселя RED, GREEN и BLUE в конструктор Color.
+0

Я undreadand теперь спасибо. –

0

Я не думаю, что это правильный ответ! Если у вас есть файл ppm с весом = 2 и высотой = 3, и вы хотите вернуть getpixel (2,1). У вас есть (1,1) (1,2) (1,3) (2,1) (2,2) (2,3), и каждый элемент имеет 3 компонента, поэтому , если вы хотите получить пиксель (2 , 1) вы должны вернуть 10 (красных), 11 (серых), 12 (синих) элементов.

Смежные вопросы