Sobel Algorithm Problem

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <cmath>
using namespace std;
void gray_process(int& blue, int& green, int& red)
{
int gray = (blue+red+green)/3;
blue = gray;
green = gray;
red = gray;
}

int get_int (fstream& stream, int offset)
{
stream.seekg(offset);
int result = 0;
int base =1;
for(int i = 0; i<4; i++)
{
result = result+ stream.get()*base;
base = base*256;

}
return result;
}


int get_pixel(int x, int y , int& pos, int start, int width, int height,fstream& stream)
{
pos=start;
pos+= (((y)*width)*3) + ((x)*3);

}


int main()
{
int gx_matrix[3][3]= {(-1,0,1),(-2,0,2),(-1,0,1)};
int gy_matrix[3][3]= {(1,2,1),(0,0,0),(-1,-2,-1)};
cout<<"Please enter the file name: "<<endl;
string filename;
cin>>filename;
fstream stream;
int blue,red,green;

stream.open(filename.c_str(), ios::in | ios::out| ios::binary);

int file_size = get_int(stream,2);

int start = get_int(stream,10);



int width = get_int (stream,18);

int height = get_int(stream,22);

int scanline_size = width * 3;
int padding = 0;

if(scanline_size%4 != 0)
{
padding=4-scanline_size%4;
}
if(file_size != start +(scanline_size + padding)*height)
{
cout<<"Not a 24-bit true color image file"<<endl;
return 1;
}
int pos = start;
for(int y = 0; y < height ; y++)
{
for(int x = 0; x< width ; x++)
{

int sumx =0; int sumy = 0; int sum = 0; int blue_2; int red_2; int green_2,pix,piy;
if(y == 0|| y == height-1 || x ==0 || x== width-1)
{
stream.seekg(pos);

sum = 0;

}
else
{
for(int i = -1; i <= 1; i++)
{
for(int j = -1 ; j<=1; j++)
{
pix = j+x;
piy = i+y;


get_pixel(pix,piy,pos,start,width,height,stream);


stream.seekg(pos);
blue = stream.get();
green = stream.get();
red = stream.get();

gray_process(blue,green,red);

sumx+= blue * gx_matrix[j+1][i+1];
sumy += blue * gy_matrix [j+1][i+1];

}
}
sum = abs(sumx)+abs(sumy);

}

if(sum >= 255)
{

blue_2 =255; green_2 = 255; red_2= 255;

}
else if(sum <0)
{

blue_2 =0; green_2 = 0; red_2=0;

}

stream.seekg(pos);
stream.put(blue_2);
stream.put(green_2);
stream.put(red_2);
stream.clear();
stream.seekg(0, ios::beg);
}
}
return 0;
}



My purpose is making sobel algorithm using c++. I made above code but it doesnt runnning well. It makes white all pixels. Any help I'll be appreaciated. Thanks.
Don't do it in-place.

Also, it would be a lot clearer if you just load your file in a matrix.
Last edited on
Topic archived. No new replies allowed.