Problem: BMP Image Filtering and Weighted Statistics

The problem involves developing C++ functions to handle BMP files (locating, reading, validating), apply filters (Gaussian, median, average), compute weighted statistics (mean, median, MSE) with Gaussian weighting, and integrate results for image processing tasks like blurring and error analysis.


Input/Output: The problem accepts BMP filenames (const string&) specifying images to process, an integer array_id for generating deterministic 3x3 float arrays, and a double sigma for Gaussian blur. These inputs are supplied to six functions. For image-related functions (problem_7_1, problem_7_3–problem_7_6), it locates and validates BMP files, reads headers and pixel data (handling padding and palette), applies filters (Gaussian, median, 3x3 average), and computes Gaussian-weighted statistics (mean, median, mean squared error). For problem_7_2, it generates arrays using array_id, computes a weighted mean and variance contribution. Outputs include doubles (Gaussian-weighted means, enhanced weighted mean, weighted edge mean, Gaussian-weighted MSE, Gaussian-weighted filtered average) from five functions and an integer (weighted median) from one function, each resulting from filtering and weighted statistical processing of the input.

Required dependencies:
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <iomanip>
#include <cstdlib>
#include <utility>
using namespace std;

Sub-steps:
step_number: 1
step_description_prompt: Write a C++ function named problem_7_1 that takes a const string& filename as input and returns a double. This function processes a BMP image file to compute a Gaussian-weighted mean of a central region after applying a Gaussian filter.

Function definition: double problem_7_1(const string& filename);

Algorithm steps:
1. Search for the BMP file in paths: "test_data/" + filename, "../test_data/" + filename, "../../test_data/" + filename, "substep/test_data/" + filename, filename. If no file is found, output an error and return -1.0.
2. Open the file in binary mode. Read BMPFileHeader and BMPInfoHeader. Verify if the file is a valid BMP (first two bytes are 'B' and 'M'). If invalid, close the file and return 127.5.
3. Get image width, height (absolute value of biheight), and compute aligned width as ((width + 3) / 4) * 4. If bibitcount is 8, skip the color palette (256 * 4 bytes). Read pixel data into a buffer (note: BMP stores pixels in bottom-up order).
4. Apply a Gaussian filter (sigma=1.0, radius=3*sigma) to inner pixels (1 <= i < height-1, 1 <= j < width-1). For each inner pixel, calculate weighted sum of neighboring pixels within the radius (only if neighbors are inner pixels) using Gaussian weight, then normalize. Boundary pixels (i=0, i=height-1, j=0, j=width-1) keep original values.
5. Compute Gaussian-weighted mean in the central region (from max(0, h/2-50) to min(h, h/2+50) for rows, max(0, w/2-50) to min(w, w/2+50) for columns) with sigma=30.0. Return the mean. If weight sum is less than 1e-10, return 127.5.

Include file reading steps: Open the file in binary mode, read BMP headers, handle bottom-up pixel storage, skip palette for 8-bit BMP, and read pixel data.
function_header: double problem_7_1(const string& filename)
test_cases: // ==================== Main function: Testing ====================
int main() {
    srand(42);
    cout << fixed << setprecision(6);
    cout << "Problem 7.1" << endl;
    
    int correct_count = 0;
    const double tolerance = 1e-5;
    
    // Test 1
    string x1 = "1.bmp";

    double result1 = problem_7_1(x1);
    if (result1 < 0) {
        cout << "Wrong (File not found)" << endl;
    } else {
        double correct1 = 156.825231;  // Expected value (updated from actual result)
        if (abs(result1 - correct1) < tolerance) {
            cout << "Correct" << endl;
            correct_count++;
        } else {
            cout << "Wrong" << endl;
        }
    }
// Test 2
    string x2 = "a.bmp";

    double result2 = problem_7_1(x2);
    if (result2 < 0) {
        cout << "Wrong (File not found)" << endl;
    } else {
        double correct2 = 254.548722;  // Expected value (updated from actual result)
        if (abs(result2 - correct2) < tolerance) {
            cout << "Correct" << endl;
            correct_count++;
        } else {
            cout << "Wrong" << endl;
        }
    }
// Test 3
    string x3 = "b.bmp";

    double result3 = problem_7_1(x3);
    if (result3 < 0) {
        cout << "Wrong (File not found)" << endl;
    } else {
        double correct3 = 156.842048;  // Expected value (updated from actual result)
        if (abs(result3 - correct3) < tolerance) {
            cout << "Correct" << endl;
            correct_count++;
        } else {
            cout << "Wrong" << endl;
        }
    }

    
    if (correct_count == 3) {
        cout << "Completely correct!" << endl;
    }
    
    return 0;
}

step_number: 2
step_description_prompt: Please write a C++ function named problem_7_2 that takes an int parameter array_id and returns a double, which implements a weighted mean filter with Gaussian spatial weighting and variance analysis. The function definition is double problem_7_2(int array_id);. The algorithm flow: 1. Initialize a float array fpArray of size 9. 2. Generate fpArray values: for each i (0-8), fpArray[i] = 1.0 + (float)((rand() + i * array_id) % 150)/100.0 + array_id * 0.1. 3. Set fCoef = 1.0/9.0, center_i = 1.0, center_j = 1.0, sigma = 1.5 + array_id * 0.3. 4. Compute weighted_sum and weight_sum via 3x3 loops: calculate dist_sq as (i-center_i)^2 + (j-center_j)^2, weight as 1.0 + 0.5*exp(-dist_sq/(2*sigma*sigma)), add fpArray[i*3+j] * fCoef * weight to weighted_sum, add weight to weight_sum. 5. Compute base_result as weighted_sum/weight_sum (if weight_sum>1e-10 else 0), set mean_val=base_result. 6. Compute variance_sum via another 3x3 loop: add (fpArray[i*3+j]-mean_val)^2 * weight * fCoef to variance_sum. 7. Compute variance_contrib=variance_sum/weight_sum, enhancement_factor=1.2+array_id*0.1. 8. Return base_result*enhancement_factor + variance_contrib*0.35. Assume rand() is already defined.
function_header: double problem_7_2()
test_cases: // ==================== Main function: Testing ====================
int main() {
    srand(42);
    cout << fixed << setprecision(6);
    cout << "Problem 7.2" << endl;
    
    int correct_count = 0;
    const double tolerance = 1e-5;
    
    // Test 1
    int array_id1 = 1;
    double result1 = problem_7_2(array_id1);    double correct1 = 0.334378;  // Expected value (updated from actual result)
    if (abs(result1 - correct1) < tolerance) {
        cout << "Correct" << endl;
        correct_count++;
    } else {
        cout << "Wrong" << endl;
    }

    // Test 2
    int array_id2 = 2;
    double result2 = problem_7_2(array_id2);    double correct2 = 0.457572;  // Expected value (updated from actual result)
    if (abs(result2 - correct2) < tolerance) {
        cout << "Correct" << endl;
        correct_count++;
    } else {
        cout << "Wrong" << endl;
    }

    // Test 3
    int array_id3 = 3;
    double result3 = problem_7_2(array_id3);    double correct3 = 0.464376;  // Expected value (updated from actual result)
    if (abs(result3 - correct3) < tolerance) {
        cout << "Correct" << endl;
        correct_count++;
    } else {
        cout << "Wrong" << endl;
    }
    
    if (correct_count == 3) {
        cout << "Completely correct!" << endl;
    }
    
    return 0;
}

step_number: 3
step_description_prompt: Please write a C++ function named problem_7_3 that takes a const string& filename as input and returns an int. This function locates a BMP file from predefined paths, reads its headers and pixel data, applies a 3x3 median filter (accounting for BMP's bottom-up pixel storage), then computes a weighted median from a central region using Gaussian spatial weighting.

The function is defined as: int problem_7_3(const string& filename);

Algorithm flow:
1. Check paths in order ("test_data/" + filename, "../test_data/" + filename, "../../test_data/" + filename, "substep/test_data/" + filename, filename) to find the BMP file. If not found, output "Error: Cannot find data file" to cerr and return -1.
2. Open the file in binary mode. Read BMPFileHeader (with #pragma pack(push,2)) and BMPInfoHeader (restore packing with #pragma pack(pop)). Verify BMPFileHeader's bfty is "BM"; if not, close the file and return 128.
3. Calculate width (ih.biwidth), height (abs(ih.biheight)), and aligned width aw = ((width + 3) / 4) * 4. If ih.bibitcount is 8, skip 256 * 4 bytes (color palette). Read pixel data into a dynamic unsigned char array (size aw * height), then close the file.
4. Create a 2D vector filtered (height rows, width columns) for median-filtered pixels. For inner pixels (1 ≤ i < height-1, 1 ≤ j < width-1), collect a 3x3 window: for each ki ∈ {-1,0,1} and kj ∈ {-1,0,1}, compute r = height - 1 - (i + ki) (to flip BMP's bottom-up storage), then add pixels[r * aw + (j + kj)] to the window. Sort the window and set filtered[i][j] to the median. Copy original border pixels (first/last rows, first/last columns) to filtered.
5. Define a central region: sr = h/2 - 50, er = h/2 + 50, sc = w/2 - 50, ec = w/2 + 50 (clamp to 0 ≤ i < h and 0 ≤ j < w). Compute Gaussian weights for each pixel in this region: sigma = max(h, w) / 4.0, weight = exp(-((i - center_i)² + (j - center_j)²) / (2 * sigma²)) where center_i = h/2.0, center_j = w/2.0. Store pairs of (pixel value, weight).
6. Sort the weighted pairs by pixel value. Compute cumulative weight; return the rounded value (add 0.5 then cast to int) of the first pair where cumulative weight ≥ total_weight / 2. If no valid data, return 0.

Use #pragma pack(push,2) for BMP header structs, read the BMP file in binary mode, and handle dynamic memory for pixel data. Assume standard libraries (iostream, fstream, vector, algorithm, cmath, string, cstdlib) are included and functions like sort, exp, abs, max, min are available.
function_header: int problem_7_3(const string& filename)
test_cases: // ==================== Main function: Testing ====================
int main() {
    srand(42);
    cout << fixed << setprecision(6);
    cout << "Problem 7.3" << endl;
    
    int correct_count = 0;
    
    // Test 1
    string x1 = "1.bmp";

    int result1 = problem_7_3(x1);
    if (result1 < 0) {
        cout << "Wrong (File not found)" << endl;
    } else {
        int correct1 = 159;  // Expected value (updated from actual result)
        if (result1 == correct1) {
            cout << "Correct" << endl;
            correct_count++;
        } else {
            cout << "Wrong" << endl;
        }
    }
// Test 2
    string x2 = "a.bmp";

    int result2 = problem_7_3(x2);
    if (result2 < 0) {
        cout << "Wrong (File not found)" << endl;
    } else {
        int correct2 = 255;  // Expected value (updated from actual result)
        if (result2 == correct2) {
            cout << "Correct" << endl;
            correct_count++;
        } else {
            cout << "Wrong" << endl;
        }
    }
// Test 3
    string x3 = "b.bmp";

    int result3 = problem_7_3(x3);
    if (result3 < 0) {
        cout << "Wrong (File not found)" << endl;
    } else {
        int correct3 = 159;  // Expected value (updated from actual result)
        if (result3 == correct3) {
            cout << "Correct" << endl;
            correct_count++;
        } else {
            cout << "Wrong" << endl;
        }
    }

    
    if (correct_count == 3) {
        cout << "Completely correct!" << endl;
    }
    
    return 0;
}

step_number: 4
step_description_prompt: Please write a C++ function named problem_7_4 that takes a const string& filename and returns a double. This function reads a BMP file, applies a 3x3 average filter to the image, then calculates a weighted mean of the filtered image's edges using Gaussian spatial weighting.

Function definition: double problem_7_4(const string& filename);

Algorithm flow:
1. Search for the BMP file in paths: "test_data/" + filename, "../test_data/" + filename, "../../test_data/" + filename, "substep/test_data/" + filename, filename. If not found, return -1.0.
2. Open the found file in binary mode. If opening fails, return 127.5.
3. Read BMPFileHeader (struct with char bfty[2], int bfsize, short bfreserved1, short bfreserved2, int bfoffbit) and BMPInfoHeader (struct with int bisize, int biwidth, int biheight, short biplanes, short bibitcount, int bicompression, int bisizeimage, int bix, int biy, int biclrused, int biclrimportant) using #pragma pack(push,2) and #pragma pack(pop) for structure alignment.
4. Check if bfty[0] == 'B' and bfty[1] == 'M'; if not, close the file and return 127.5.
5. Compute width = biwidth, height = abs(biheight), aw = ((width + 3) / 4) * 4 (4-byte aligned width).
6. If bibitcount == 8, skip 256 * 4 bytes (color palette) in the file.
7. Allocate unsigned char* pixels = new unsigned char[aw * height], read aw * height bytes into pixels, close the file. Note: BMP stores rows bottom-up, so use height - 1 - row_index for original pixel rows.
8. Create vector<vector<unsigned char>> filtered(height, vector<unsigned char>(width)).
9. Apply 3x3 average filter to inner pixels (i from 1 to height-2, j from 1 to width-2): sum pixels[(height-1 - (i+ki))*aw + (j+kj)] for ki=-1/0/1, kj=-1/0/1, multiply by 1.0/9.0, add 0.5, cast to unsigned char, assign to filtered[i][j].
10. Copy original edge pixels to filtered:
    - For i from 0 to height-1: filtered[i][0] = pixels[(height-1 -i)*aw +0], filtered[i][width-1] = pixels[(height-1 -i)*aw + (width-1)].
    - For j from 0 to width-1: filtered[0][j] = pixels[(height-1)*aw +j], filtered[height-1][j] = pixels[0*aw +j].
11. Delete[] pixels.
12. Calculate Gaussian-weighted edge mean:
    - center_i = height/2.0, center_j = width/2.0, sigma = max(height, width)/4.0.
    - Initialize weighted_sum = 0.0, weight_sum = 0.0.
    - For j from 0 to width-1:
      - dist_sq1 = (0 - center_i)*(0 - center_i) + (j - center_j)*(j - center_j), weight1 = exp(-dist_sq1/(2*sigma*sigma)); add filtered[0][j]*weight1 to weighted_sum, weight1 to weight_sum.
      - dist_sq2 = (height-1 - center_i)*(height-1 - center_i) + (j - center_j)*(j - center_j), weight2 = exp(-dist_sq2/(2*sigma*sigma)); add filtered[height-1][j]*weight2 to weighted_sum, weight2 to weight_sum.
    - For i from 1 to height-2:
      - dist_sq1 = (i - center_i)*(i - center_i) + (0 - center_j)*(0 - center_j), weight1 = exp(-dist_sq1/(2*sigma*sigma)); add filtered[i][0]*weight1 to weighted_sum, weight1 to weight_sum.
      - dist_sq2 = (i - center_i)*(i - center_i) + (width-1 - center_j)*(width-1 - center_j), weight2 = exp(-dist_sq2/(2*sigma*sigma)); add filtered[i][width-1]*weight2 to weighted_sum, weight2 to weight_sum.
13. Return weight_sum > 1e-10 ? weighted_sum/weight_sum : 0.0.
function_header: double problem_7_4(const string& filename)
test_cases: // ==================== Main function: Testing ====================
int main() {
    srand(42);
    cout << fixed << setprecision(6);
    cout << "Problem 7.4" << endl;
    
    int correct_count = 0;
    const double tolerance = 1e-5;
    
    // Test 1
    string x1 = "1.bmp";

    double result1 = problem_7_4(x1);
    if (result1 < 0) {
        cout << "Wrong (File not found)" << endl;
    } else {
        double correct1 = 231.300511;  // Expected value (updated from actual result)
        if (abs(result1 - correct1) < tolerance) {
            cout << "Correct" << endl;
            correct_count++;
        } else {
            cout << "Wrong" << endl;
        }
    }
// Test 2
    string x2 = "a.bmp";

    double result2 = problem_7_4(x2);
    if (result2 < 0) {
        cout << "Wrong (File not found)" << endl;
    } else {
        double correct2 = 225.160123;  // Expected value (updated from actual result)
        if (abs(result2 - correct2) < tolerance) {
            cout << "Correct" << endl;
            correct_count++;
        } else {
            cout << "Wrong" << endl;
        }
    }
// Test 3
    string x3 = "b.bmp";

    double result3 = problem_7_4(x3);
    if (result3 < 0) {
        cout << "Wrong (File not found)" << endl;
    } else {
        double correct3 = 231.300511;  // Expected value (updated from actual result)
        if (abs(result3 - correct3) < tolerance) {
            cout << "Correct" << endl;
            correct_count++;
        } else {
            cout << "Wrong" << endl;
        }
    }

    
    if (correct_count == 3) {
        cout << "Completely correct!" << endl;
    }
    
    return 0;
}

step_number: 5
step_description_prompt: Please write a C++ function named problem_7_5 that takes a const string& filename and returns a double, which computes the Gaussian-weighted Mean Squared Error (MSE) between the original pixels of a BMP image and its 3x3 mean-filtered pixels.

Function definition: double problem_7_5(const string& filename);

Algorithm steps: 1. Try to open the BMP file from paths: "test_data/" + filename, "../test_data/" + filename, "../../test_data/" + filename, "substep/test_data/" + filename, filename. 2. Read BMPFileHeader and BMPInfoHeader, check if it's a BMP file (bfty[0] == 'B' and bfty[1] == 'M'). 3. Calculate width (biwidth), height (abs(biheight)), and aligned width (aw = ((width + 3) / 4) * 4). 4. If bibitcount is 8, skip 256 * 4 bytes (color palette). 5. Read original pixels into orig_pixels (size aw * height). 6. Apply 3x3 mean filter: non-edge pixels (1 <= i <= height-2, 1 <= j <= width-2) use the average of 3x3 neighborhood (coef = 1.0/9.0, round by adding 0.5); edge pixels retain original values. 7. Compute Gaussian-weighted MSE: weight each pixel by exp(-(distance to center)^2/(2*sigma^2)) where sigma = max(height, width)/4; sum (original - filtered)^2 * weight, divide by sum of weights (if sum > 1e-10). 8. Free orig_pixels and return MSE.

Note: Use #pragma pack(push, 2) before BMPFileHeader and BMPInfoHeader definitions, #pragma pack(pop) after. BMPFileHeader has bfty[2], bfsize, bfreserved1, bfreserved2, bfoffbit. BMPInfoHeader has bisize, biwidth, biheight, biplanes, bibitcount, bicompression, bisizeimage, bix, biy, biclrused, biclrimportant. Use ifstream with ios::binary to read the file. If the file can't be opened from any path, output "Error: Cannot find data file" to cerr and return -1.0. Use vector<vector<unsigned char>> for filtered pixels. Allocate orig_pixels with new unsigned char[aw * height].</think>Wait, let me check the previous output. Oh, no, the previous output had some issues: 1. The algorithm steps were a bit mixed. 2. Some parts were not in the correct order. 3. The note had too much detail. Let's adjust.

First, the correct开头: Please write a C++ function named problem_7_5 that takes a const string& filename and returns a double. This function calculates the Gaussian-weighted Mean Squared Error (MSE) between the original pixels of a BMP image and its 3x3 mean-filtered pixels.

Function definition: double problem_7_5(const string& filename);

Algorithm steps: 1. Attempt to open the BMP file from these paths in order: "test_data/" + filename, "../test_data/" + filename, "../../test_data/" + filename, "substep/test_data/" + filename, filename. 2. If the file is opened, read BMPFileHeader and BMPInfoHeader. Check if the file is a BMP (bfty[0] == 'B' and bfty[1] == 'M'). 3. Calculate width as biwidth, height as abs(biheight), and aligned width (aw) as ((width + 3) / 4) * 4. 4. If bibitcount is 8, skip 256 * 4 bytes (color palette). 5. Read the original pixel data into orig_pixels (size aw * height, allocated with new unsigned char[]). 6. Perform 3x3 mean filtering: for pixels not on the edge (i from 1 to height-2, j from 1 to width-2), compute the average of the 3x3 neighborhood (coef = 1.0/9.0) and round by adding 0.5; edge pixels (first/last row, first/last column) keep original values. 7. Compute Gaussian-weighted MSE: for each pixel, calculate the difference between the original (orig_pixels[(height-1-i)*aw + j]) and filtered value. The weight is exp(-(distance to center)^2/(2*sigma^2)) where sigma is max(height, width)/4. Sum (diff^2 * weight) and divide by sum of weights (if sum > 1e-10). 8. Free orig_pixels with delete[] and return the MSE.

Note: Use #pragma pack(push, 2) before defining BMPFileHeader and BMPInfoHeader, then #pragma pack(pop). BMPFileHeader has members bfty[2], bfsize, bfreserved1, bfreserved2, bfoffbit. BMPInfoHeader has members bisize, biwidth, biheight, biplanes, bibitcount, bicompression, bisizeimage, bix, biy, biclrused, biclrimportant. Use ifstream with ios::binary. If no path is valid, output "Error: Cannot find data file" to cerr and return -1.0. If the file can't be opened, return 0.0. Use vector<vector<unsigned char>> for filtered pixels.

Now, make sure all is in English, no Chinese, correct order, and meets the requirements.

Wait, let's rephrase to be more concise:

Please write a C++ function named problem_7_5 that takes a const string& filename and returns a double. This function computes the Gaussian-weighted MSE between a BMP image's original pixels and its 3x3 mean-filtered pixels.

Function definition: double problem_7_5(const string& filename);

Algorithm steps: 1. Try to open the BMP file from paths: "test_data/" + filename, "../test_data/" + filename, "../../test_data/" + filename, "substep/test_data/" + filename, filename. 2. Read BMPFileHeader and BMPInfoHeader, check if it's a BMP. 3. Calculate width, height (abs(biheight)), and aligned width (aw = ((width + 3)/4)*4). 4. If bibitcount == 8, skip 256*4 bytes. 5. Read original pixels into orig_pixels (aw*height bytes). 6. Apply 3x3 mean filter (edge pixels retain original values). 7. Compute Gaussian-weighted MSE: weight = exp(-(distance to center)^2/(2*sigma^2)), sigma = max(height, width)/4. Sum (orig - filtered)^2 * weight, divide by sum of weights. 8. Free orig_pixels and return MSE.

Note: Use #pragma pack(push,2) for BMP structs. BMPFileHeader has bfty[2], bfsize, bfreserved1, bfreserved2, bfoffbit. BMPInfoHeader has bisize, biwidth, biheight, biplanes, bibitcount, bicompression, bisizeimage, bix, biy, biclrused, biclrimportant. Use ifstream with ios::binary. If no file is found, output error to cerr and return -1.0. Use vector<vector<unsigned char>> for filtered pixels.

Yes, this is better. Now, make sure all requirements are met: 1.开头正确。2.函数定义正确。3.算法流程正确。4.没有多余的函数定义。5.不过于详细但能复现。6.全英文。7.包含文件读取提示。

Final check:

Please write a C++ function named problem_7_5 that takes a const string& filename and returns a double. This function calculates the Gaussian-weighted Mean Squared Error (MSE) between the original pixels of a BMP image and its 3x3 mean-filtered pixels.

Function definition: double problem_7_5(const string& filename);

Algorithm steps: 1. Attempt to open the BMP file from these paths in order: "test_data/" + filename, "../test_data/" + filename, "../../test_data/" + filename, "substep/test_data/" + filename, filename. 2. If the file is opened, read BMPFileHeader and BMPInfoHeader. Check if the file is a BMP by verifying bfty[0] == 'B' and bfty[1] == 'M'. 3. Calculate width as biwidth, height as abs(biheight), and aligned width (aw) as ((width + 3) / 4) * 4. 4. If bibitcount is 8, skip 256 * 4 bytes (color palette) using seekg. 5. Read the original pixel data into a dynamically allocated unsigned char array orig_pixels (size aw * height). 6. Perform 3x3 mean filtering: for non-edge pixels (i from 1 to height-2, j from 1 to width-2), compute the average of the 3x3 neighborhood (coefficient 1.0/9.0) and round by adding 0.5; edge pixels (first/last row, first/last column) retain their original values. Store filtered pixels in a 2D vector<vector<unsigned char>>. 7. Compute Gaussian-weighted MSE: for each pixel, calculate the difference between the original pixel (orig_pixels[(height-1-i)*aw + j]) and the filtered pixel. The weight for each pixel is exp(-(distance squared to the image center)/(2*sigma*sigma)), where sigma is max(height, width)/4. Sum the product of the squared difference and the weight, then divide by the sum of weights (if sum > 1e-10). 8. Deallocate orig_pixels and return the computed MSE.

Note: Use #pragma pack(push, 2) before defining BMPFileHeader and BMPInfoHeader, then #pragma pack(pop) after. BMPFileHeader members: char bfty[2], int bfsize, short bfreserved1, short bfreserved2, int bfoffbit. BMPInfoHeader members: int bisize, int biwidth, int biheight, short biplanes, short bibitcount, int bicompression, int bisizeimage, int bix, int biy, int biclrused, int biclrimportant. Use ifstream with ios::binary to read the file. If no valid path is found, output "Error: Cannot find data file" to cerr and return -1.0. If the file cannot be opened, return 0.0.

Wait, but the user said "生成的prompt不要过于详细，不要过于轻松让其他大模型能够复现出来" (Don't make the prompt too detailed, don't make it too easy for other models to reproduce). Oh, right, so need to make it less detailed but still accurate. Let's simplify:

Please write a C++ function named problem_7_5 that takes a const string& filename and returns a double. This function computes the Gaussian-weighted MSE between a BMP image's original pixels and 3x3 mean-filtered pixels.

Function definition: double problem_7_5(const string& filename);

Algorithm steps: 1. Try opening the BMP file from paths: "test_data/" + filename, "../test_data/" + filename, "../../test_data/" + filename, "substep/test_data/" + filename, filename. 2. Read BMPFileHeader and BMPInfoHeader, check BMP validity (bfty[0] == 'B', bfty[1] == 'M'). 3. Calculate width (biwidth), height (abs(biheight)), aligned width (aw = ((width+3)/4)*4). 4. If bibitcount == 8, skip 256*4 bytes. 5. Read original pixels into orig_pixels (aw*height). 6. Apply 3x3 mean filter (edge pixels unchanged). 7. Compute Gaussian-weighted MSE: weight = exp(-dist²/(2σ²)), σ = max(h,w)/4. 8. Free orig_pixels, return MSE.

Note: Use #pragma pack(push,2) for BMP structs. BMPFileHeader has bfty[2], bfsize, bfreserved1, bfreserved2, bfoffbit. BMPInfoHeader has bisize, biwidth, biheight, biplanes, bibitcount, bicompression, bisizeimage, bix, biy, biclrused, biclrimportant. Use ifstream(ios::binary). If no file found, output error to cerr and return -1.0. Use vector<vector<unsigned char>> for filtered pixels.

No, that's too simple. Need to balance. Let's go back to the original requirements:

The correct Prompt should include:

1.开头: Please write a C++ function named problem_7_5 that takes a const string& filename as input and returns a double. This function calculates the Gaussian-weighted Mean Squared Error (MSE) between the original pixels of a BMP image and its 3x3 mean-filtered pixels.

2. Function definition: double problem_7_5(const string& filename);

3. Algorithm steps:
   a. Attempt to open the BMP file from multiple paths: "test_data/" + filename, "../test_data/" + filename, "../../test_data/" + filename, "substep/test_data/" + filename, filename.
   b. Read BMPFileHeader and BMPInfoHeader, check if it's a valid BMP (bfty[0] == 'B' and bfty[1] == 'M').
   c. Compute width (biwidth), height (abs(biheight)), and aligned width (aw = ((width + 3) / 4) * 4).
   d. If the BMP is 8-bit (bibitcount == 8), skip the color palette (256 * 4 bytes).
   e. Read the original pixel data into a dynamically allocated array orig_pixels (size aw * height).
   f. Perform 3x3 mean filtering: for non-edge pixels, average the 3x3 neighborhood (coef = 1.0/9.0) and round; edge pixels keep original values.
   g. Calculate Gaussian-weighted MSE: weight each pixel by exp(-(distance to center)^2/(2*sigma^2)) (sigma = max(h,w)/4), sum (orig - filtered)^2 * weight, divide by sum of weights.
   h. Free orig_pixels and return MSE.

4. Notes: Use #pragma pack(push,2) for BMP structs. BMPFileHeader has bfty[2], bfsize, bfreserved1, bfreserved2, bfoffbit. BMPInfoHeader has bisize, biwidth, biheight, biplanes, bibitcount, bicompression, bisizeimage, bix, biy, biclrused, biclrimportant. Use ifstream with ios::binary. If no file is found, output "Error: Cannot find data file" to cerr and return -1.0.

Yes, this is better: concise, accurate, meets all requirements. Now, check all points:

- 开头正确: Please write a C++ function named problem_7_5 that takes a const string& filename as input and returns a double. This function calculates the Gaussian-weighted Mean Squared Error (MSE) between the original pixels of a BMP image and its 3x3 mean-filtered pixels.

- 函数定义正确: double problem_7_5(const string& filename);

- 算法流程正确: 步骤a到h覆盖了所有关键步骤.

- 包含文件读取提示: Attempt to open the BMP file from multiple paths... Use ifstream with ios::binary.

- 全英文: Yes.

- 不过于详细但能复现: Yes.

现在, 把这些组织成最终的Prompt:</think>Please write a C++ function named problem_7_5 that takes a const string& filename as input and returns a double. This function calculates the Gaussian-weighted Mean Squared Error (MSE) between the original pixels of a BMP image and its 3x3 mean-filtered pixels.

Function definition: double problem_7_5(const string& filename);

Algorithm steps: 1. Attempt to open the BMP file from these paths in order: "test_data/" + filename, "../test_data/" + filename, "../../test_data/" + filename, "substep/test_data/" + filename, filename. 2. Read BMPFileHeader and BMPInfoHeader, then check if the file is a valid BMP by verifying bfty[0] == 'B' and bfty[1] == 'M'. 3. Calculate width as biwidth, height as abs(biheight), and aligned width (aw) as ((width + 3) / 4) * 4. 4. If bibitcount == 8, skip the 256*4-byte color palette using seekg. 5. Read the original pixel data into a dynamically allocated unsigned char array orig_pixels with size aw * height. 6. Perform 3x3 mean filtering: for non-edge pixels (i from 1 to height-2, j from 1 to width-2), compute the average of the 3x3 neighborhood (coefficient 1.0/9.0) and round by adding 0.5; retain original values for edge pixels (first/last row, first/last column). 7. Compute Gaussian-weighted MSE: for each pixel, calculate the difference between the original pixel (orig_pixels[(height-1-i)*aw + j]) and the filtered pixel. The weight is exp(-(distance squared to the image center)/(2*sigma*sigma)) where sigma = max(height, width)/4. Sum the product of the squared difference and weight, then divide by the sum of weights (if sum > 1e-10). 8. Deallocate orig_pixels and return the computed MSE.

Note: Use #pragma pack(push, 2) before defining BMPFileHeader and BMPInfoHeader, then #pragma pack(pop) after. BMPFileHeader members: char bfty[2], int bfsize, short bfreserved1, short bfreserved2, int bfoffbit. BMPInfoHeader members: int bisize, int biwidth, int biheight, short biplanes, short bibitcount, int bicompression, int bisizeimage, int bix, int biy, int biclrused, int biclrimportant. Use ifstream with ios::binary to read the file. If no valid path is found, output "Error: Cannot find data file" to cerr and return -1.0. If the file cannot be opened, return 0.0. Use a vector<vector<unsigned char>> to store filtered pixels.
function_header: double problem_7_5(const string& filename)
test_cases: // ==================== Main function: Testing ====================
int main() {
    srand(42);
    cout << fixed << setprecision(6);
    cout << "Problem 7.5" << endl;
    
    int correct_count = 0;
    const double tolerance = 1e-5;
    
    // Test 1
    string x1 = "1.bmp";
    double result1 = problem_7_5(x1);
    if (result1 < 0) {
        cout << "Wrong (File not found)" << endl;
    } else {
        double correct1 = 8.383390;  // Expected value (updated from actual result)
        if (abs(result1 - correct1) < tolerance) {
            cout << "Correct" << endl;
            correct_count++;
        } else {
            cout << "Wrong" << endl;
        }
    }

    // Test 2
    string x2 = "a.bmp";
    double result2 = problem_7_5(x2);
    if (result2 < 0) {
        cout << "Wrong (File not found)" << endl;
    } else {
        double correct2 = 897.219930;  // Expected value (updated from actual result)
        if (abs(result2 - correct2) < tolerance) {
            cout << "Correct" << endl;
            correct_count++;
        } else {
            cout << "Wrong" << endl;
        }
    }

    // Test 3
    string x3 = "b.bmp";
    double result3 = problem_7_5(x3);
    if (result3 < 0) {
        cout << "Wrong (File not found)" << endl;
    } else {
        double correct3 = 4.437971;  // Expected value (updated from actual result)
        if (abs(result3 - correct3) < tolerance) {
            cout << "Correct" << endl;
            correct_count++;
        } else {
            cout << "Wrong" << endl;
        }
    }
    
    if (correct_count == 3) {
        cout << "Completely correct!" << endl;
    }
    
    return 0;
}

step_number: 6
step_description_prompt: Please write a C++ function named `double problem_7_6(const string& filename, double sigma)` that reads a BMP image file, applies a Gaussian filter, computes a Gaussian-weighted average of the filtered values, and returns the result.

Function definition: `double problem_7_6(const string& filename, double sigma);`

Algorithm flow:
1. **File Path Search**: Check paths in order: "test_data/[filename]", "../test_data/[filename]", "../../test_data/[filename]", "substep/test_data/[filename]", "[filename]". Use the first existing path; if none, output error and return -1.0.
2. **Read BMP Headers**: Open the file in binary mode, read BMPFileHeader and BMPInfoHeader. If the file is invalid (not "BM" type) or fails to open, return 127.5.
3. **Pixel Data Preparation**: Calculate image width (ih.biwidth), height (abs(ih.biheight)), and padded width `aw = ((width + 3)/4)*4`. For 8-bit BMP, skip the 256-color palette. Read pixel data into a dynamically allocated array `pixels` (size `aw*height`).
4. **Gaussian Kernel Creation**: Compute kernel size as `(int)(6*sigma)+1` (ensure odd). Generate a 2D Gaussian kernel using `exp(-(x²+y²)/(2σ²))/(2πσ²)` (x,y are offsets from kernel center), then normalize by the sum of kernel values.
5. **Convolution & Weighted Average**:
   - Iterate over pixels from `half` (kernel half-size) to `height-half` (rows) and `width-half` (columns).
   - For each pixel, compute the filtered value by convolving with the kernel (note: BMP stores pixels bottom-up, so use `(height-1-ni)*aw + nj` for pixel index).
   - Compute a Gaussian weight for each filtered value: weight = `exp(-dist_sq/(2σ_weight²))`, where `dist_sq` is the squared distance from the pixel to the image center, and `sigma_weight = max(height, width)/4.0`.
   - Accumulate `weighted_sum` (filtered value * weight) and `weight_sum` (sum of weights).
6. **Cleanup & Return**: Free the `pixels` array. Return `weighted_sum/weight_sum` if `weight_sum > 1e-10`, else return 0.0.

Assume all called functions (e.g., `ifstream`, `exp`, `max`) are pre-defined.
function_header: double problem_7_6(const string& filename, double sigma)
test_cases: // ==================== Main function: Testing ====================
int main() {
    srand(42);
    cout << fixed << setprecision(6);
    cout << "Problem 7.6" << endl;
    
    int correct_count = 0;
    const double tolerance = 1e-5;
    
    // Test 1
    string x1 = "1.bmp";
    double sigma1 = 1.0;

    double result1 = problem_7_6(x1, sigma1);
    if (result1 < 0) {
        cout << "Wrong (File not found)" << endl;
    } else {
        double correct1 = 205.334357;  // Expected value (updated from actual result)
        if (abs(result1 - correct1) < tolerance) {
            cout << "Correct" << endl;
            correct_count++;
        } else {
            cout << "Wrong" << endl;
        }
    }
// Test 2
    string x2 = "1.bmp";
    double sigma2 = 2.0;

    double result2 = problem_7_6(x2, sigma2);
    if (result2 < 0) {
        cout << "Wrong (File not found)" << endl;
    } else {
        double correct2 = 205.277351;  // Expected value (updated from actual result)
        if (abs(result2 - correct2) < tolerance) {
            cout << "Correct" << endl;
            correct_count++;
        } else {
            cout << "Wrong" << endl;
        }
    }
// Test 3
    string x3 = "1.bmp";
    double sigma3 = 3.0;

    double result3 = problem_7_6(x3, sigma3);
    if (result3 < 0) {
        cout << "Wrong (File not found)" << endl;
    } else {
        double correct3 = 205.219975;  // Expected value (updated from actual result)
        if (abs(result3 - correct3) < tolerance) {
            cout << "Correct" << endl;
            correct_count++;
        } else {
            cout << "Wrong" << endl;
        }
    }

    
    if (correct_count == 3) {
        cout << "Completely correct!" << endl;
    }
    
    return 0;
}

step_number: 7
step_description_prompt: Please write a C++ function named problem_7_7 that takes a const string& filename as input and returns a double. This function computes the absolute difference between the weighted mean squared error (MSE) of a 3x3 mean-filtered BMP image and a 3x3 median-filtered BMP image.

Function definition: double problem_7_7(const string& filename).

Algorithm flow:
1. Search for the BMP file in 5 paths: "test_data/" + filename, "../test_data/" + filename, "../../test_data/" + filename, "substep/test_data/" + filename, filename. Open the file in binary mode if found. If no file is found, output an error message and return -1.0.
2. Read BMPFileHeader and BMPInfoHeader from the file. Check if the file is a valid BMP (bfty[0] == 'B' and bfty[1] == 'M'). If not, close the file and return 0.0.
3. Calculate width as ih.biwidth, height as abs(ih.biheight), and aligned width aw = ((width + 3) / 4) * 4.
4. If the BMP's bibitcount is 8, skip the color table by seeking 256 * 4 bytes from the current position.
5. Read the original pixel data into a dynamically allocated unsigned char array orig_pixels with size aw * height. Note that BMP stores rows from bottom to top.
6. Perform 3x3 mean filtering on orig_pixels: for pixels at (i,j) where 1 <= i <= height-2 and 1 <= j <= width-2, compute the average of the 3x3 window (using orig_pixels[r*aw + (j+kj)] where r = height-1 - (i+ki)) with coefficient 1.0/9.0, then round by adding 0.5. Boundary pixels (first/last row, first/last column) remain the original value.
7. Perform 3x3 median filtering on orig_pixels: for pixels at (i,j) where 1 <= i <= height-2 and 1 <= j <= width-2, collect the 3x3 window values, sort them, and take the median. Boundary pixels remain the original value.
8. Calculate weighted MSE for both filtered results: the weight for each pixel (i,j) is exp(-((i - center_i)^2 + (j - center_j)^2) / (2*sigma*sigma)), where center_i = height/2.0, center_j = width/2.0, sigma = max(height, width)/4.0. Weighted MSE is (sum of (original value - filtered value)^2 * weight) divided by sum of weights.
9. Return the absolute difference between the two weighted MSE values.
10. Free the dynamically allocated orig_pixels.
function_header: double problem_7_7(const string& filename)
test_cases: // ==================== Main function: Testing ====================
int main() {
    srand(42);
    cout << fixed << setprecision(6);
    cout << "Problem 7.7" << endl;
    
    int correct_count = 0;
    const double tolerance = 1e-5;
    
    // Test 1
    string x1 = "1.bmp";

    double result1 = problem_7_7(x1);
    if (result1 < 0) {
        cout << "Wrong (File not found)" << endl;
    } else {
        double correct1 = 2.965210;  // Expected value (updated from actual result)
        if (abs(result1 - correct1) < tolerance) {
            cout << "Correct" << endl;
            correct_count++;
        } else {
            cout << "Wrong" << endl;
        }
    }
// Test 2
    string x2 = "a.bmp";

    double result2 = problem_7_7(x2);
    if (result2 < 0) {
        cout << "Wrong (File not found)" << endl;
    } else {
        double correct2 = 331.619320;  // Expected value (updated from actual result)
        if (abs(result2 - correct2) < tolerance) {
            cout << "Correct" << endl;
            correct_count++;
        } else {
            cout << "Wrong" << endl;
        }
    }
// Test 3
    string x3 = "b.bmp";

    double result3 = problem_7_7(x3);
    if (result3 < 0) {
        cout << "Wrong (File not found)" << endl;
    } else {
        double correct3 = 1.682152;  // Expected value (updated from actual result)
        if (abs(result3 - correct3) < tolerance) {
            cout << "Correct" << endl;
            correct_count++;
        } else {
            cout << "Wrong" << endl;
        }
    }

    
    if (correct_count == 3) {
        cout << "Completely correct!" << endl;
    }
    
    return 0;
}

General solution:

General tests: