c++ - 如何将结构转换为无符号字符,反之亦然?
问题描述
我目前正在尝试编写一个函数,允许用户读取图像,他们可以水平或垂直翻转图像,或者将图像转换为灰度。我无法让灰度功能正常工作。
错误提示“操作数 []”不匹配(操作数类型为“图像”和“整数”)。另一个错误是“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;
}
}
}
这是我正在使用的头文件:
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)
声明一个函数,返回 NOTHING 并获取一个图像、一个像素、一个宽度和一个高度
Image newImage[width][height];
创建一个图像数组的数组
color[0] = i % 256;
unsigned char red = color[0];
将一个值写入color[0]
(可能会或可能不会做某事,具体取决于您是否有正确的复制构造函数),然后您直接将该值复制到其中red
以进行进一步处理。
我建议重新考虑您的图像结构,因为在当前状态下它无法存储图像(至少不是您可能想要的方式。)
一种方法是将像素定义为一个像素:
struct Pixel {
uint8_t r, g, b;
};
和图像作为宽度,高度和很多像素。
struct Image {
int width, height;
std::vector<Pixel> pixels;
};
toGrayscale 应该有签名:
Image toGrayscale(const Image& image);
意思是一个函数返回一个图像并获取一个对现有图像的常量(不可修改)引用。
然后您可以使用创建一个新图像(名为 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();
表示该函数不接受任何参数并且不返回任何内容,而它可能至少应该采用保存图像的位置(可能是const std::filesystem::path&
orconst std::string&
或const char*
)并返回图像。
推荐阅读
- javascript - 这个开玩笑的测试设置有什么问题?
- javascript - 如何在 JSDoc 和 TypeScript 中编写原型的参数类型?
- python - 如果用户提供相同的输入超过 X 时间打印一些东西
- swift - 如何防止浮动调色板窗口被视为文档
- r - 从光栅砖创建的数据框太大并且很多零值
- reactjs - 如何在 React 应用程序中重新渲染 Uppy 实例时保留我已经上传的图像的图像预览
- android - 谷歌云平台和 Firebase 存储有什么联系?
- python - 尝试在 TensorFlow 中使用带有回调的数据生成器时出现值错误
- docker - Pacemaker 可以用于故障转移到第二个 docker 主机吗?
- python - 我在游戏中实现了暂停功能,但是当我按下键盘上的 p 键时,它只会暂停我的汽车精灵