阿摩線上測驗 登入

申論題資訊

試卷:103年 - 103年專門職業及技術人員高等建築師、技師、第二次食品技師暨普通不動產經紀人、記帳士考高等_資訊技師#29113
科目:程式設計
年份:103年
排序:0

題組內容

二、假設有一灰階影像 img1,其類別為 Image 如下:
class Image {
private:
int width; // 寬
int height; // 高
unsigned char **pixel; // 像素
public:
Image(int w, int h); // 建構子
unsigned char getpixel(int r, int c); // 取出 pixel[r][c]值
void setpixel(int r, int c, unsigned char g);// 設定 pixel[r][c]值為 g
int getwidth(); // 取出影像的寬度
int getheight(); // 取出影像的高度
}
其寬為 width,高為 height,其像素值存在一個二維陣列 pixel 中,資料型態為 unsigned
char。今欲將此灰階影像 img1 順時針旋轉 90 度,並儲存在另一新的灰階影像 img2。

申論題內容

⑵試完成 Image 類別的其他成員函式:getpixel( ),setpixel( ),getwidth( ),和
getheight( ),並寫出一個 PrtImg( )函式如下,列印影像 img 參數中 pixel 的值,其
中每一列(row)印完需跳行,像素值以空白隔開。(10 分)
void PrtImg(Image & img)
{
……
}

詳解 (共 1 筆)

詳解 提供者:hchungw
根據題目的要求,下面將提供在 C++ 中 Image 類的成員函數 getpixel(), setpixel(), getwidth(), getheight() 的實現,以及一個 PrtImg() 函數來列印 Image 物件的圖元值。
首先是 Image 類的其他成員函數的實現:
cpp
Copy code
class Image {
private:
    int width; // 寬
    int height; // 高
    unsigned char **pixel; // 圖元
public:
    // 構造函數
    Image(int w, int h) : width(w), height(h) {
        pixel = new unsigned char*[height];
        for (int i = 0; i < height; ++i) {
            pixel[i] = new unsigned char[width];
        }
    }
    // 解構函數
    ~Image() {
        for (int i = 0; i < height; ++i) {
            delete[] pixel[i];
        }
        delete[] pixel;
    }
    // 獲取圖元值
    unsigned char getpixel(int r, int c) {
        if (r >= 0 && r < height && c >= 0 && c < width) {
            return pixel[r][c];
        } else {
            // 如果索引超出範圍,返回一個預設值
            return 0;
        }
    }
    // 設置圖元值
    void setpixel(int r, int c, unsigned char g) {
        if (r >= 0 && r < height && c >= 0 && c < width) {
            pixel[r][c] = g;
        }
    }
    // 獲取寬度
    int getwidth() {
        return width;
    }
    // 獲取高度
    int getheight() {
        return height;
    }
};
接下來,實現 PrtImg() 函數:
cpp
Copy code
void PrtImg(Image &img) {
    for (int i = 0; i < img.getheight(); ++i) {
        for (int j = 0; j < img.getwidth(); ++j) {
            std::cout << static_cast<int>(img.getpixel(i, j)) << " ";
        }
        std::cout << std::endl;
    }
}
在 PrtImg() 函數中,通過兩層迴圈遍歷 Image 物件的 pixel 陣列。在內層迴圈中,列印每一行的圖元值,並用空格隔開。每列印完一行後,外層迴圈使得輸出換行,以開始新一行的列印。
請注意,這裡的 getpixel() 函數做了越界檢查,如果傳入的行號或列號超出了圖元陣列的範圍,函數會返回一個預設值(在這個例子中是 0)。同樣,在 setpixel() 函數中,也進行了越界檢查,以防止無效的記憶體訪問。當圖元值被列印時,由於 unsigned char 可能不會以數值形式列印,因此我們使用了 static_cast<int>() 來確保輸出為整數。