Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
Tips and Traps¶
cv2.imread
returns a numpy ndarray in Python. This is different fromPIL.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.OpenCV uses the
BGR
representation of an image when storing it as a numpy array. This is different from Pillow which uses theRGB
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 supportBGR
even if it hasmode
parameter).cv2.imwrite
support writing to different format of image, and the format of the output image is determined by the file extension.
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 ...
!curl -sSL -o 4h.png https://user-images.githubusercontent.com/824507/128439087-0c935d86-bb34-4c2c-8e69-6d78b3022833.png
arr = cv2.imread("4h.png")
Image.fromarray(np.flip(arr, 2))
cv2.copyMakeBorder¶
arr2 = cv2.copyMakeBorder(
arr, 9, 9, 9, 9, borderType=cv2.BORDER_CONSTANT, value=(0, 255, 0)
)
Image.fromarray(np.flip(arr2, 2))
cv2.addWeighted¶
cv2.addWeighted(target_img, 0.8, red_img, 0.2, 0)