// Convert image to sepia
void sepia(int height, int width, RGBTRIPLE image[height][width])
{
int i = 0;
int j = 0;
int oRed;
int oGreen;
int oBlue;
int sepiaBlue;
int sepiaGreen;
int sepiaRed;
for (i = 0; i < height; i++)
{
for (j = 0; j < width; j++)
{
oRed = image[i][j].rgbtRed;
oGreen = image[i][j].rgbtGreen;
oBlue = image[i][j].rgbtBlue;
sepiaRed = round((.393 * oRed) + (.769 * oGreen) + (.189 * oBlue));
sepiaGreen = round((.349 * oRed) + (.686 * oGreen) + (.168 * oBlue));
sepiaRed = round((.272 * oRed) + (.534 * oGreen) + (.131 * oBlue));
if (sepiaRed > 255)
{
sepiaRed = 255;
}
if (sepiaGreen > 255)
{
sepiaGreen = 255;
}
if (sepiaBlue > 255)
{
sepiaBlue = 255;
}
image[i][j].rgbtRed = sepiaRed;
image[i][j].rgbtGreen = sepiaGreen;
image[i][j].rgbtBlue = sepiaBlue;
}
}
return;
}
检查结果:
使用像素(20、40、90)进行测试 运行./测试 1 0... 检查输出“56 50 39 “…… 预期输出: 56 50 39 实际输出: 39 50 0
当我非常确定我使用了正确的公式时,它只是输出错误的 RGB 值。 如下所示,连一个像素都无法正确。不知道问题出在哪里。
处理重复代码(复制/粘贴)时很容易出现无意识的盲目性。
眼光敏锐的读者会看到两个
sepiaRed = round((...
尝试编写更多紧凑代码,并使用可简化水平和垂直扫描的布局和变量名称:
// 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++ ) {
int red = image[i][j].rgbtRed;
int grn = image[i][j].rgbtGreen;
int blu = image[i][j].rgbtBlue;
int sred = round((.393 * red) + (.769 * grn) + (.189 * blu));
int sgrn = round((.349 * red) + (.686 * grn) + (.168 * blu));
int sblu = round((.272 * red) + (.534 * grn) + (.131 * blu));
image[i][j].rgbtRed = (sred > 255) ? 255 : sred;
image[i][j].rgbtGreen = (sgrn > 255) ? 255 : sgrn;
image[i][j].rgbtBlue = (sblu > 255) ? 255 : sblu;
}
}
}