【发布时间】:2019-03-20 10:11:06
【问题描述】:
我在周末关注 Ray Tracing 一书,其中作者使用纯 C++ 制作了一个小型 Ray Tracer,结果是一个 PPM 图像。
作者代码
生成此 PPM 图像。
所以作者建议作为一个练习,让程序通过stb_image 库生成一个JPG 图像。到目前为止,我尝试像这样更改原始代码:
#include <fstream>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
struct RGB{
unsigned char R;
unsigned char G;
unsigned char B;
};
int main(){
int nx = 200;
int ny = 100;
struct RGB data[nx][ny];
for(int j = ny - 1 ; j >= 0 ; j-- ){
for(int i = 0; i < nx ; i++){
float r = float(i) / float(nx);
float g = float(j) / float(ny);
float b = 0.2;
int ir = int(255.99 * r);
int ig = int(255.99 * g);
int ib = int(255.99 * b);
data[i][j].R = ir;
data[i][j].G = ig;
data[i][j].B = ib;
}
}
stbi_write_jpg("image.jpg", nx, ny, 3, data, 100);
}
结果如下:
如您所见,我的结果略有不同,我不知道为什么。 主要问题是:
黑色显示在屏幕的左上角,并且通常颜色不会以从左到右、从上到下的正确顺序显示。
图像被“分割”成两半,结果实际上是作者的原始图像,但却是成对产生的????
可能我对 STB_IMAGE_WRITE 的使用方式有误解,所以如果有使用此库经验的人能告诉我发生了什么,我将不胜感激。
编辑 1 我在 cmets 中实现了 @1201ProgramAlarm 建议的更改,并将 struct RGB data[nx][ny] 更改为 struct RGB data[ny][nx] ,so the result now is this。
【问题讨论】:
-
您可以尝试
sizeof(struct RGB)而不是3。我怀疑发生的事情是 stbi_write_jpg 没有以您期望的方式从data中读取图像数据。 -
@craig65535 我按照你的建议做了,但没有运气。我仍然得到相同的结果。非常感谢你试图帮助我。我对自己没有得到它感到非常愤怒。
标签: c++ raytracing stb-image