簡體   English   中英

如何將結構轉換為無符號字符,反之亦然?

[英]How do I convert a struct to an unsigned char and vice versa?

我目前正在嘗試編寫一個 function 允許用戶讀取圖像,他們可以水平或垂直翻轉圖像,或將圖像轉換為灰度。 我無法讓灰度 function 工作。

錯誤提示“操作數 []”不匹配(操作數類型為“圖像”和“整數”)。 另一個錯誤是“operator=”不匹配(操作數類型是“Image”和“unsigned char”)。

我怎樣才能得到它,以便代碼可以正確運行?

void toGrayScale(Image image, Pixel pixel, int width, int height)
{
    Image newImage[width][height];
    for (int i = 0; i < width; i++){
        for (int j = 0; j < height; j++) {
            unsigned char color[] = image[width][height];
            color[0] = i % 256;
            unsigned char red = color[0];
            color[1] = j % 256;
            unsigned char green = color[1];
            color[2] = (i * j) % 256;
            unsigned char blue = color[2];
            unsigned char gray = round(0.299*red + 0.587*green + 0.114*blue);
            newImage[i][j] = gray;
        }
    }
}

這是我正在使用的 header 文件:

struct Pixel {    
    int numRows;
    int numCols;
    char color[];
    int red;
    int green;
    int blue;
};

struct Image {
    int width;
    int height;
    int size;
    Pixel pixel;
};

 // loads a "P3" PPM  formatted image from a file
void loadImage();

 // saves an image to a text file as a "P3" PPM formatted image
void saveImage();

 // filters an image by converting it to grayscale
void toGrayscale(struct Image);

 // manipulates an image by flipping it either vertically or horizontally
void flipImage(struct Image, bool horizontal);

您的代碼中有一些對我來說沒有多大意義的東西

void toGrayScale(Image image, Pixel pixel, int width, int height)

聲明一個 function 返回 NOTHING 並獲取一個圖像、一個像素、一個寬度和一個高度

Image newImage[width][height];

創建圖像的 arrays 數組

color[0] = i % 256;
unsigned char red = color[0];

將一個值寫入color[0] (可能會或可能不會做某事,取決於您是否有正確的復制構造函數),然后您直接將該值復制到red以進行進一步處理。

我建議重新考慮您的圖像結構,因為在當前的 state 中,它無法存儲圖像(至少不是您可能想要的方式。)

一種方法是將像素定義為一個像素:

struct Pixel {
    uint8_t r, g, b;
};

和圖像作為寬度,高度和很多像素。

struct Image {
    int width, height;
    std::vector<Pixel> pixels;
};

toGrayscale 應該有簽名:

Image toGrayscale(const Image& image);

意思是 function 返回圖像並對現有圖像進行常量(不可修改)引用。

然后您可以使用創建一個新圖像(名為 newImage)

Image newImage{ WIDTH, HEIGHT, std::vector<Pixels>( WIDTH * HEIGHT )};

要獲取循環中的顏色值,您可以使用:

uint8_t red = image.pixels[j * width + i].r;

並將灰度值寫入新圖像,您可以使用

newImage.pixels[j * width + i].r = newImage.pixels[j * width + i].g = newImage.pixels[j * width + i].b = gray;

最后,您可以使用return newImage返回您的圖像。

您可能還應該重新考慮其他功能的簽名,例如

void loadImage();

說 function 不需要 arguments 並且什么都不返回,而它可能至少應該占用保存圖像的位置(可能是const std::filesystem::path&const std::string&const char* )並返回圖片。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM