CS50 Week4无滤镜模糊函数异常求助:编译正常但模糊效果错误
3×3图像模糊函数异常排查求助
我花了几天时间排查这个Blur函数的问题,它能正常编译,但图像模糊效果异常。我怀疑是数值或公式出错,反复检查数小时仍未找到问题。
本次作业要求使用3×3模糊框实现图像模糊:将模糊框内有效(在图像边界内)像素的RGB值求和,除以有效像素数量,再将模糊后的值赋值给图像。
但我生成的模糊图像完全无法分辨原有内容,我参考过其他模糊函数的实现,也多次从零重写代码尝试不同变体,但都无效。以下代码是我认为最接近正确实现的版本,恳请各位帮忙排查问题。
// Blur image void blur(int height, int width, RGBTRIPLE image[height][width]) { // create image copy for holding modifies RGB values RGBTRIPLE copy[height][width]; for(int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { copy[i][j] = image[i][j]; } } // setting variable for holding sum of blur box RGB values float blurred = 0.0; float blurgreen = 0.0; float blurblue = 0.0; // setting counter for valid blur box pixels float validpixels = 0.0; // looping through image rows for( int i = 0; i < height; i++) { // looping through image columns for(int j = 0; j < width; j++) { // looping through blur box rows for(int r = -1; r < 2; r++) { //looping through blur box columns for(int c = -1; c < 2; c++) { // counting only valid blur-box pixels(inside image boundaries) if(i + c >= 0 && j + r >= 0 && i + c < height && j + r < width) { // storing total of blur box RGB values blurred += copy[i + c][j + r].rgbtRed; blurgreen += copy[i + c][j + r].rgbtGreen; blurblue += copy[i + c][j + r].rgbtBlue; // counting valid pixels total validpixels ++; } } } // calculate RGB blurred values and assigning them to image copy copy[i][j].rgbtRed = round(blurred / validpixels); copy[i][j].rgbtGreen = round(blurgreen / validpixels); copy[i][j].rgbtBlue = round(blurblue / validpixels); } } //giving blur values back to image for(int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { image[i][j].rgbtRed = copy[i][j].rgbtRed; image[i][j].rgbtGreen = copy[i][j].rgbtGreen; image[i][j].rgbtBlue = copy[i][j].rgbtBlue; } } return; }
内容的提问来源于stack exchange,提问作者Nico
相关产品推荐
相关产品推荐

