Reputation: 21
I am used to programming in python and am trying to teach a friend how to program in c. I was able to teach him the basics but he has an exam coming up soon that I would love to be able to help him with, however I myself am having trouble converting some code from python to c. One question he was given for example..
the program should read the greyscale pixel values from the pixelsIn.txt.file using a loop. The lines of the file are read in by the program. The body of the image contains the grey scale value of each body in the picture and the program should determine whether the pixel value is equal to 110, if so, the program should convert this pixel value to 225 (white) otherwise it should be converted back to 0 (black).
If I was to do that in python I would read in each line, split the line and then use a for loop to check if the number is 110 or not. However I am extremely unsure if this is how it would be done in C? Sorry if I am being vague but I will answer any questions if I wasn't clear enough. Any help would be greatly appreciated.
For example in the following tiny image on the left, the letter H is encoded using the pixel value 110. This is not very clear on the left hand image as the surrounding pixels have a greyscale value which is very close. If the message pixel values are changed to 255 (white) and the non-message pixel values changed to 0 (black) the image on the right hand side then shows the hidden H clearly
Upvotes: 1
Views: 845
Reputation: 897
I will consider that you already opened the image in FILE *image
, read the header P2
of the image, saved its width to int width
and height to int height
and read the maximum intensity 255
.
You will just need to iterate on each pixel of image
using fscanf
to read each integer. Here is a sample code in C:
int i, j, **matrix = malloc(height * sizeof(int *));
for (i = 0; i < height; i++) {
matrix[i] = malloc(width * sizeof(int))
for (j = 0; j < width; j++) {
int pixel;
fscanf(image, "%d", &pixel);
matrix[i][j] = (pixel == 110) ? 255 : 0;
}
}
After that, your changed image will be at matrix. You just have to save it.
Hope it helped.
Upvotes: 1