|
这是一个用Sobel法来提取图像边缘的程序,,编译不出来,,,
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#define max_buf 64
#define ON 1
#define OFF 0
#define X_SIZE 800
#define Y_SIZE 600
#define R 0
#define G 1
#define B 2
void get_header(FILE *fin, char head[][max_buf])
{
char str[max_buf];
int head_flag=ON, head_count=0, i, j;
for(i=0;i<3;i++){
for(j=0;j<max_buf;j++){
head[j] = '\0';
}
}
while(head_flag==ON){
if(fgets(str, max_buf, fin) != NULL){
if(str[0] != '#'){
i=0;
while(str != '\0'){
head[head_count] = str;
i++;
}
head_count++;
}
if(head_count == 3)
head_flag = OFF;
}
}
}
void get_image(FILE *fin, unsigned char
in[Y_SIZE][X_SIZE][3])
{
int i, j;
for(i=0;i<Y_SIZE;i++){
for(j=0;j<X_SIZE;j++){
fread(in[j], 3, 1, fin);
}
}
}
void gray_scale(unsigned char in[Y_SIZE][X_SIZE][3],
unsigned char out[Y_SIZE][X_SIZE][3])
{
int i, j, k, red, blue, green;
double gray;
for(i=0;i<Y_SIZE;i++){
for(j=0;j<X_SIZE;j++){
red = in[j][R];
blue = in[j][G];
green = in[j][B];
gray = 0.299*red + 0.587*blue + 0.114*green;
for(k=0;k<3;k++)
out[j][k] = (unsigned char)gray;
}
}
}
void monochrome(unsigned char in[Y_SIZE][X_SIZE][3],
unsigned char out[Y_SIZE][X_SIZE][3], int threshold)
{
int i, j, k;
for(i=0;i<Y_SIZE;i++){
for(j=0;j<X_SIZE;j++){
for(k=0;k<3;k++){
if(in[j][k] > threshold) out[j][k] = 0xff;
else out[j][k] =
0x00;
}
}
}
}
void sobel(unsigned char in[Y_SIZE][X_SIZE][3], unsigned
char out[Y_SIZE][X_SIZE][3])
{
int i, j, k;
int fx, fy;
double sum, fxy;
for(i=1;i<Y_SIZE-1;i++){
for(j=1;j<X_SIZE-1;j++){
for(k=0;k<3;k++){
fx = in[i-1][j-1][k]*(-1) + in[i+1][j-1][k]
+ in[i-1][j][k]*(-2) + in[i+1][j][k]*2
+ in[i-1][j+1][k]*(-1) + in[i+1][j+1][k];
fy = in[i-1][j-1][k]*(-1) + in[j-1][k]*(-2) +
in[i+1][j-1][k]*(-1)
+ in[i-1][j+1][k] + in[j+1][k]*2 + in[i+1][j+1][k];
sum = pow(fx,2)+pow(fy,2);
fxy = sqrt(sum);
if(fxy>255) fxy = 255;
else if(fxy<0) fxy = 0;
out[j][k] = (unsigned char)fxy;
}
}
}
}
void put_image(FILE *fout, char head[][max_buf], unsigned
char out[Y_SIZE][X_SIZE][3])
{
int i;
for(i=0;i<3;i++)
fprintf(fout, "%s", head);
fwrite(out, sizeof(char), Y_SIZE*X_SIZE*3, fout);
}
int main(int argc, char **argv)
{
FILE *fin ,*fout;
char head[3][max_buf];
int threshold;
unsigned char input[Y_SIZE][X_SIZE][3];
unsigned char gray[Y_SIZE][X_SIZE][3];
unsigned char mono[Y_SIZE][X_SIZE][3];
unsigned char output[Y_SIZE][X_SIZE][3];
if(argc != 4){
printf("Usage: ./a.out in.ppm out.ppm
threshold_value\n");
exit(1);
}
fout = fopen(argv[2], "w");
fin = fopen(argv[1], "r");
threshold = atoi(argv[3]);
get_header(fin, head);
get_image(fin, input);
gray_scale(input, gray);
monochrome(gray, mono, threshold);
sobel(mono, output);
put_image(fout, head, output);
fclose(fin);
fclose(fout);
return(0);
} |
|