I've been trying to turn an image black and white, and then rotate it 90 degrees in C but i'm fairly new to programming, this is what i have to far.
#include<stdio.h>
#include<string.h>
int main () {
FILE* first;
FILE* second;
FILE* third;
int counter;
char c;
int width, height, pixelmax, average;
int pixelred, pixelgreen, pixelblue, black[300][300][3];
int i, j, timer=0;
int k, f=0;
first=fopen("blackbuck.ppm","r");
second=fopen("blacktrout.ppm","w");
this skips the first few lines of code
for(counter=1;counter<3;counter++){
do{
c=getc(first);
}while(c != '\n');
}
fscanf(first,"%d%d", &width,&height);
fscanf(first,"%d", &pixelmax);
in this part of the program, i turn the pixels to black and white by taking their average, this is the easy part.
for(i=0, j=0; i<width;i++, timer++){
fscanf(first,"%d%d%d",&pixelred,&pixelgreen,&pixelblue);
average=(pixelred+pixelgreen+pixelblue)/3;
black[i][j][0]=average;
black[i][j][1]=average;
black[i][j][2]=average;
fprintf(second,"%d %d %d\n",black[i][j][0],black[i][j][1],black[i][j][2]);
if (i==(width-1)&& j<height){
i=0;
j++;
}
}
fclose(first);
fclose(second);
third=fopen("blackflip.ppm","w");
This is the part where i am completely lost, i have no idea how to rotate the pixels stores in my 3d array 90 degrees. Any help please? A well explained explanation would go a long way for a newbie programmer like myself. thanks!
for(...???)
}
}
return 0;
The basic logic is like this:
Let's say that (0,0) is the upper-left corner, and we are wanting to rotate left 90 degrees. Then the upper-left corner of the rotated image is equivalent to the upper-right corner of the original image, which is at (original_height-1,0).
As you go across the top of the image, increasing, x, you are grabbing pixels from the original image along the right side, increasing y, so the x of your rotated image is like the y of the original image.
As you go down in the rotated_image, increasing y, you are moving more to the left of the original_image, which is why we're subtracting rotated_y from original_height-1 to get the original_x coordinate.
Another thing to notice is that the width and height of the rotated image are reversed from the orignal image.
In general you can rotate a point alpha degrees clockwise using the next formula Let a point P(x,y) Let alpha the degrees you want to rotate clockwise
Then x_rotated = x*cos(alpha) - y*sin(alpha); y_rotated = x*sin(alpha) + y*cos(alpha);
and if alpha is 90 degrees clockwise then
x_rotated = -y; y_rotated = x;
I hope this would be helpful