Python 3 and OpenCV Part 2: How to Load an Image with OpenCV (and render it with GeeXLab)

GeeXLab - Python 3 - How to load and image with OpenCV


This second tutorial will show you how to load an image with OpenCV and how to convert it to a GeeXLab texture for rendering.

An OpenCV image is a NumPy array (numpy.ndarray). NumPy is one of the most important libraries for scientific computing in Python. It provides all you need to work with multidimensional arrays. This article is not a tutorial about NumPy. I added some links about Numpy at the end of the article.

To load an image with OpenCV, we use the imread() function:

import cv2
demo_dir = gh_utils.get_demo_dir() 		
cv_image = cv2.imread(demo_dir + 'data/kool-image.jpg', cv2.IMREAD_COLOR)

The size of the image can be retrieved with:

im_height, img_width = cv_image.shape[0:2]

Now let’s see how to create a regular GeeXLab texture from this OpenCV image.

PF_U8_RGB = 1
PF_U8_BGR = 2
PF_U8_RGBA = 3
# BGR U8 is the default pixel format of OpenCV images.
# We create an empty texture
tex_image = gh_texture.create_2d(img_width, img_height, PF_U8_BGR)
# and we update the texture pixmap with the OpenCV image.
gh_texture.update_gpu_memory_from_numpy_img(tex_image, cv_image)

It’s done! We have now an GeeXLab texture filled with the data of an OpenCV image. It’s a detail but it can save you some time to know that OpenCV stores image pixels in BGR format…

The demo displays two images: the normal image and a smaller version of the same image. The smaller version has been created with the OpenCV resize() function:

img2_width = int(round(img_width/3))
img2_height = int(round(img_height/3))
cv_image2 = cv2.resize(cv_image,(img2_width, img2_height),interpolation=cv2.INTER_LINEAR)

Another useful function is copyMakeBorder(). This function adds a border to an image. Here is the way to add a red border of 10 pixels:

cv_image2 = cv2.copyMakeBorder(cv_image2,
  value=(0, 0, 255))

For the color value, keep in mind that the pixel format is BGR…

Here is the demo:

GeeXLab - Python 3 - How to load and image with OpenCV


Leave a Comment

Your email address will not be published. Required fields are marked *