使用OpenCV提取矩阵

索拉卜

我在使用OpenCV提取矩阵(裁剪)时遇到了一些麻烦。有趣的是,如果我不执行该行来“裁剪”图像,则一切正常。但是,如果这样做,我会在图像的位置看到水平的彩色线条。

这是为了表明正确进行了裁剪。

cv::imshow("before", newimg);

//the line that "crops" the image
newimg = newimg(cv::Rect(leftcol, toprow, rightcol - leftcol, bottomrow - toprow));

cv::imshow("after", newimg);

裁剪前后

接下来的代码是将图像绑定到纹理的位置,以便可以在OpenGL中使用它。

glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, newimg.cols, newimg.rows,
    0, GL_BGR, GL_UNSIGNED_BYTE, newimg.ptr());
glBindTexture(GL_TEXTURE_2D, 0);

以后再画。

float h = size;
float w = size * aspectRatio; // of the image. aspectRatio = width / height
glEnable(GL_TEXTURE_2D);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
glBindTexture(GL_TEXTURE_2D, texture);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex3f(x, y, z);
glTexCoord2f(0.0f, 1.0f); glVertex3f(x, y + h, z);
glTexCoord2f(1.0f, 1.0f); glVertex3f(x + w, y + h, z);
glTexCoord2f(1.0f, 0.0f); glVertex3f(x + w, y, z);
glEnd();
glDisable(GL_TEXTURE_2D);

All of this works well and I see the proper image drawn in the OpenGL window when I comment out that line in which I had cropped the image. I have checked the image type before and after the cropping, but the only difference seems to be the reduced number of rows and columns in the final image.

Here is the image that gets drawn when cropping has been done.

裁剪时产生的影像

Saurabh

After a bit of research I found out a way to solve the problem. The reason the image was looking distorted was because though the image had been cropped, newimg.step / newimg.elemSize() still showed the original size of the image. This meant that only the values of rows and columns had changed in the output image but pixels with no data in them which were no part of the image remained. That is possibly why the "after" image has a gray area on the right. I might be wrong about this theory since I don't have a deep understanding of the subject but it all started working properly once I inserted this line before calling glTexImage2D:

glPixelStorei(GL_UNPACK_ROW_LENGTH, newimg.step / newimg.elemSize());

Note: Since we are manipulating the pixel store of OpenGL, it's best to push the state before doing so:

glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);

And pop it out after you are done:

glPopClientAttrib();

这是为了避免内存损坏。我感谢genpfault为我指出了正确的方向。

有关更多详细信息,请参见8.了解像素存储状态https://www.opengl.org/archives/resources/features/KilgardTechniques/oglpitfall/

这篇文章也非常有用。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章