Ben Chuanlong Du's Blog

It is never too late to learn.

Tips on OpenCV

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Installation

You can install OpenCV for Python using the following commands.

:::bash
sudo apt-get install libsm6 libxrender-dev
pip3 install opencv-python

If you use xinstall, you can install OpenCV for Python with the following single command.

:::bash
xinstall --sudo cv -ic

Tips and Traps

  1. cv2.imread returns a numpy ndarray in Python. This is different from PIL.Image.Image.open which returns a Pillow Image. cv2.imread can be more efficient if you want to manipulate the underlying data of image as you do not have to convert between the underlying data and image objects.

  2. OpenCV uses the BGR representation of an image when storing it as a numpy array. This is different from Pillow which uses the RGB representation of images. numpy.flip(arr, 2) might help if a library doesn't different representation of images (e.g. PIL.Image.fromarray does not support BGR even if it has mode parameter).

  3. cv2.imwrite support writing to different format of image, and the format of the output image is determined by the file extension.

In [6]:
import numpy as np
from PIL import Image
import cv2

cv2.imread returns a numpy array, however, it is in BGR mode which is different from Pillow (who uses RGB mode).

cv2 uses BGR mode ...

In [4]:
!curl -sSL -o 4h.png https://user-images.githubusercontent.com/824507/128439087-0c935d86-bb34-4c2c-8e69-6d78b3022833.png
In [7]:
arr = cv2.imread("4h.png")
Image.fromarray(np.flip(arr, 2))
Out[7]:

cv2.copyMakeBorder

In [20]:
arr2 = cv2.copyMakeBorder(
    arr, 9, 9, 9, 9, borderType=cv2.BORDER_CONSTANT, value=(0, 255, 0)
)
Image.fromarray(np.flip(arr2, 2))
Out[20]:

cv2.addWeighted

In [ ]:
cv2.addWeighted(target_img, 0.8, red_img, 0.2, 0)

Comments