如何理解CS50 Problem Set4中edges滤镜的实现代码及运行结果?
CS50 作业4:边缘滤镜(Edges)实现代码
这段代码用于完成CS50第四套作业的边缘滤镜拓展任务,核心逻辑是:先将原图像的RGBTRIPLE数据完整复制到临时数组,再遍历每个像素及其周围3×3邻域的像素,通过Sobel梯度算子(gx、gy)分别计算红、绿、蓝三个通道的梯度值,最后结合梯度值计算边缘强度并更新图像像素。
void edges(int height, int width, RGBTRIPLE image[height][width]) { RGBTRIPLE copy[height][width]; long gxRed, gxGreen, gxBlue, gyRed, gyGreen, gyBlue; int row_x, row_y, column_x, column_y, a, b; int gx_arr[3][3] = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}}; int gy_arr[3][3] = {{-1, -2, -1}, {0, 0, 0}, {1, 2, 1}}; 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++) { gxRed = 0; gxGreen = 0; gxBlue = 0; gyRed = 0; gyGreen = 0; gyBlue = 0; for (a = i - 1, row_x = 0, row_y = 0; a <= i + 1; a++, row_x++, row_y++) { for (b = j - 1, column_x = 0, column_y = 0; b <= j + 1; b++, column_x++, column_y++) { if (a < 0 || b < 0 || a > height || b > width) { continue; } gxRed += image[a][b].rgbtRed * gx_arr[row_x][column_x]; gxGreen += image[a][b].rgbtGreen * gx_arr[row_x][column_x]; gxBlue += image[a][b].rgbtBlue * gx_arr[row_x][column_x]; gyRed += image[a][b].rgbtRed * gy_arr[row_y][column_y]; gyGreen += image[a][b].rgbtGreen * gy_arr[row_y][column_y]; gyBlue += image[a][b].rgbtBlue * gy_arr[row_y][column_y]; } column_x = 0; column_y = 0; } copy[i][j].rgbtRed = fmin(round(sqrt(gxRed * gxRed + gyRed * gyRed)), 255); copy[i][j].rgbtGreen = fmin(round(sqrt(gxGreen * gxGreen + gyGreen * gyGreen)), 255); copy[i][j].rgbtBlue = fmin(round(sqrt(gxBlue * gxBlue + gyBlue * gyBlue)), 255); } } for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { image[i][j] = copy[i][j]; } } return; }
运行效果
- 测试效果1:原图经过处理后,物体的轮廓边缘被清晰提取,不同色彩区域的边界呈现高亮线条,符合边缘检测的预期。
- 测试效果2:另一组图像的处理结果显示,细节边缘保留完整,过渡自然,滤镜效果达标。
内容的提问来源于stack exchange,提问作者Rohan jain
相关产品推荐
相关产品推荐

