2D image in memory - changing to grayscale

Hello,

I'm trying to change a memory block values that is a 2d image. I'm trying to figure out how to change to change scale but it's not working.

This is the code

Vivienne

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
void Image::GenerateGrayScale(void)

    {
        // create temporary area
        unsigned char * tempdata_ = new unsigned char[width_ * height_ * depth_*components_];
        unsigned char grey;

        // loop
        for(unsigned width=0; width<width_;width++)
        {
            for(unsigned height=0; height<height_;height++)
            {
                    grey=(data_[(width*height)+0]+data_[(width*height)+1]+data_[(width*height)+2])/3;

                    tempdata_[(width*height)+0]=grey;
                    tempdata_[(width*height)+1]=grey;
                    tempdata_[(width*height)+2]=grey;
            }
        }

        // copy data
        memcpy(data_, tempdata_, width_*height_*depth_*components_);

        return;

    }


I'm trying to employ this method http://www.tannerhelland.com/3643/grayscale-image-algorithm-vb6/

Some link and to code that might be useful.

https://github.com/urho3d/Urho3D/blob/master/Source/Engine/Resource/Image.cpp

Naming your counters 'width' and 'height' is making this confusing, since they do not represent the width and height.

If you rename them to something more logical... like x and y, then the problem becomes apparent:

1
2
3
4
5
6
7
8
9
10
11
        for(unsigned x=0; x<width_;x++)
        {
            for(unsigned y=0; y<height_;y++)
            {
                    grey=(data_[(x*y)+0]+data_[(x*y)+1]+data_[(x*y)+2])/3;

                    tempdata_[(x*y)+0]=grey;
                    tempdata_[(x*y)+1]=grey;
                    tempdata_[(x*y)+2]=grey;
            }
        }


As you can hopefully see... (x*y) is not what you want. The typical way to index an image would be more like this:

 
tempdata_[ (y*width)+x ] = ...
Topic archived. No new replies allowed.