class Texture
{
public:
GLuint m_ID=0;
GLuint m_Slot=0;
std::string m_FilePath;
int m_W=0, m_H=0;
Texture(const std::string &FilePath, unsigned slot) { Create(FilePath, slot); }
void Create(const std::string& FilePath, unsigned slot)
{
m_FilePath = FilePath; m_Slot = slot;
cv::Mat I = cv::imread(FilePath, cv::ImreadModes::IMREAD_UNCHANGED); // 按照图片的原本信息读取
cv::flip(I, I, 0); // 上下翻转, opengl store image from bottom to top while opencv store image from top to bottom
m_W = I.cols; m_H = I.rows; // 图片的长宽尺寸
int channels = I.channels(); // int pixel_size = I.elemSize(); auto channel_size = I.elemSize1(); auto row_size = I.step;
// 因为opengl存储像素数据的alignment问题,需要进行如下设置才能正常显示图片
//use fast 4-byte alignment (default anyway) if possible
glPixelStorei(GL_UNPACK_ALIGNMENT, (I.step & 3) ? 1 : 4);
//set length of one complete row in data (doesn't need to equal image.cols)
glPixelStorei(GL_UNPACK_ROW_LENGTH, I.step / I.elemSize());
glGenTextures(1, &m_ID); Bind();
// filter settings: GL_NEAREST GL_LINEAR
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // when tex is scale down
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // when tex is scale up
// mipmap settings: GL_NEAREST_MIPMAP_NEAREST GL_LINEAR_MIPMAP_NEAREST GL_NEAREST_MIPMAP_LINEAR GL_LINEAR_MIPMAP_LINEAR
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
// wrap settings : GL_REPEAT, GL_MIRRORED_REPEAT GL_CLAMP_TO_EDGE GL_CLAMP_TO_BORDER
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// for GL_CLAMP_TO_BORDER
// float borderColor[] = { 1.0f, 1.0f, 0.0f, 1.0f }; glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor);
glTexImage2D(GL_TEXTURE_2D, // Type of texture
0, // Pyramid level (for mip-mapping) - 0 is the top level
channels==3? GL_RGB : GL_RGBA, // Internal colour format to convert to
m_W, // Image width i.e. 640 for Kinect in standard mode
m_H, // Image height i.e. 480 for Kinect in standard mode
0, // Border width in pixels (can either be 1 or 0)
channels == 3 ? GL_BGR : GL_BGRA, // Input image format
GL_UNSIGNED_BYTE, // Image data type
I.ptr());
glGenerateMipmap(GL_TEXTURE_2D);
Unbind();
}
void Bind() const { glActiveTexture(GL_TEXTURE0 + m_Slot); glBindTexture(GL_TEXTURE_2D, m_ID); }
void Unbind() const { glBindTexture(GL_TEXTURE_2D, 0); }
};
使用opencv为opengl提供纹理图片
最新推荐文章于 2023-04-09 13:18:45 发布