1. 程式人生 > >如何將opencv-iamge上載到opengl的紋理中

如何將opencv-iamge上載到opengl的紋理中

opencv-image-loading-for-opengl-texture

GLuint cvMat2glTexture(const cv::Mat& mat)
		{
			// https://stackoverflow.com/questions/16809833/opencv-image-loading-for-opengl-texture
			// REMARK: The image is flipped horizontally as OpenCV stores data in the opposite direction of OpenGL

			double min, max;
			cv::minMaxLoc(mat, &min, &max);
			cv::Mat img = mat;
			/*
			//why ?
			if (max > 1)
				img /= max;*/

				//mat.convertTo(mat, CV_8UC3);

				//use fast 4-byte alignment (default anyway) if possible
			glPixelStorei(GL_UNPACK_ALIGNMENT, (img.step & 3) ? 1 : 4); //printf("%i %llu ", (mat.step & 3), mat.step / mat.elemSize());

																		//set length of one complete row in data (doesn't need to equal image.cols)
			glPixelStorei(GL_UNPACK_ROW_LENGTH, static_cast<GLint>(img.step / img.elemSize()));

			GLenum internalformat = GL_RGB32F;
			if (img.channels() == 4) internalformat = GL_RGBA;
			if (img.channels() == 3) internalformat = GL_RGB;
			if (img.channels() == 2) internalformat = GL_RG;
			if (img.channels() == 1) internalformat = GL_RED;

			GLenum externalformat = GL_BGR;
			if (img.channels() == 1) externalformat = GL_RED; // GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT32F, GL_R32F NOT WORKING!

			GLuint texture;
			glGenTextures(1, &texture);
			glBindTexture(GL_TEXTURE_2D, texture);


			//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
			//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
			try {
				//internalformat = internals[k];
				glTexImage2D(GL_TEXTURE_2D,
					/* level */				0,
					/* internalFormat */	internalformat,
					/* width */				img.cols,
					/* height */			img.rows,
					/* border */			0,
					/* format */			externalformat,
					/* type */				GL_FLOAT,
					/* *data */				img.ptr());

				//glGenerateMipmap(GL_TEXTURE_2D);
			}
			catch (std::exception & e)
			{
				printf("%s.\n", e.what());
			}

			return texture;
		}