cs50/helpers.c

117 lines
3.1 KiB
C
Raw Normal View History

#include "helpers.h"
2024-03-08 14:36:32 +02:00
#include <math.h>
// Convert image to grayscale
void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
2024-03-08 14:36:32 +02:00
int avg = round((image[i][j].rgbtBlue + image[i][j].rgbtGreen + image[i][j].rgbtRed) /
(float) 3);
image[i][j].rgbtBlue = image[i][j].rgbtGreen = image[i][j].rgbtRed = avg;
}
}
return;
}
// Convert image to sepia
void sepia(int height, int width, RGBTRIPLE image[height][width])
{
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
2024-03-08 14:36:32 +02:00
int sepiaRed = round(.393 * image[i][j].rgbtRed + .769 * image[i][j].rgbtGreen +
.189 * image[i][j].rgbtBlue);
int sepiaGreen = round(.349 * image[i][j].rgbtRed + .686 * image[i][j].rgbtGreen +
.168 * image[i][j].rgbtBlue);
int sepiaBlue = round(.272 * image[i][j].rgbtRed + .534 * image[i][j].rgbtGreen +
.131 * image[i][j].rgbtBlue);
if (sepiaRed > 255)
{
sepiaRed = 255;
}
if (sepiaGreen > 255)
{
sepiaGreen = 255;
}
if (sepiaBlue > 255)
{
sepiaBlue = 255;
}
image[i][j].rgbtBlue = sepiaBlue;
image[i][j].rgbtGreen = sepiaGreen;
image[i][j].rgbtRed = sepiaRed;
}
}
return;
}
// Reflect image horizontally
void reflect(int height, int width, RGBTRIPLE image[height][width])
{
RGBTRIPLE tmp[height][width];
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
tmp[i][j] = image[i][width - j - 1];
}
}
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
image[i][j] = tmp[i][j];
}
}
return;
}
// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width])
{
RGBTRIPLE copy[height][width];
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
copy[i][j] = image[i][j];
}
}
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
2024-03-08 14:36:32 +02:00
int sumRed = 0, sumGreen = 0, sumBlue = 0, count = 0;
for (int k = (i - 1); k <= (i + 1); k++)
{
for (int l = (j - 1); l <= (j + 1); l++)
{
if ((k >= 0 && k <= (height - 1)) && (l >= 0 && l <= (width - 1)))
{
2024-03-08 14:36:32 +02:00
sumRed += copy[k][l].rgbtRed;
sumGreen += copy[k][l].rgbtGreen;
sumBlue += copy[k][l].rgbtBlue;
count++;
}
}
}
image[i][j].rgbtRed = round(sumRed / (float) count);
image[i][j].rgbtGreen = round(sumGreen / (float) count);
image[i][j].rgbtBlue = round(sumBlue / (float) count);
}
}
return;
}